uncategorized

排序去重

场景:对数组进行排序和去重

java 8 stream实现

1
2
3
4
5
List<String> list = Arrays.asList("EE", "AA","AA","BB");
list.stream()
.distinct()
.sorted()
.forEach(x -> System.out.println(x));

二叉树实现

思路: 根据数组构造一棵有序的二叉树,其中如果相等的元素忽略(去除掉)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import java.util.ArrayList;
import java.util.List;
public class BinaryTree<T extends Comparable> {
class Node {
private Node left;
private Node right;
private T data;
private boolean distinct;
public Node(T data, boolean distinct){
this.data = data;
this.distinct = distinct;
}
public void addNode(Node newNode) {
int compare = newNode.data.compareTo(this.data);
//put smaller on the left node
if (compare < 0) {
if (this.left == null) {
this.left = newNode;
} else {
this.left.addNode(newNode);
}
return;
}
//put bigger on the right node
if (compare > 0 || !this.distinct) {
if (this.right == null) {
this.right = newNode;
} else {
this.right.addNode(newNode);
}
return;
}
}
public void toList(List<T> list){
if (this.left != null) {
this.left.toList(list);
}
list.add(this.data);
if (this.right != null) {
this.right.toList(list);
}
}
}
private Node root;
private boolean distinct;
public BinaryTree() {
this.distinct = false;
}
public BinaryTree(boolean distinct) {
this.distinct = distinct;
}
public List<T> sort(Iterable<T> iterable) {
for (T data : iterable){
Node newNode = new Node(data, this.distinct);
if (this.root == null) {
this.root = newNode;
} else {
this.root.addNode(newNode);
}
}
List<T> result = new ArrayList<>();
if (this.root == null) {
return result;
}
this.root.toList(result);
return result;
}
public static void main(String[] args){
List<String> list = Arrays.asList("EE", "BB", "AA","AA","BB");
BinaryTree<String> bt = new BinaryTree(true);
List<String> result = bt.sort(list);
for (String k : result){
System.out.println(k);
}
}
}