Skip to content

Commit 7fbdd2e

Browse files
committed
fd
1 parent d56217d commit 7fbdd2e

File tree

2 files changed

+53
-20
lines changed

2 files changed

+53
-20
lines changed

solution/src/main/java/com/inuker/solution/CountOfSmallerNumbersAfterSelf.java

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,12 @@
99

1010
/**
1111
* 这题理解了好久才搞明白
12-
* 建立一棵二叉树,从数组末尾开始遍历,这里每个树的节点要记录sum和dup,dup表示到当前为止,该节点重复的次数
13-
* sum表示该节点左子树中的节点总数,注意如果有的节点有重复也要算上。现在假如遍历到了数组中的第i个数,则其右边的所有数
14-
* 都已经生成了节点插到树中,此时我们只要统计从树的root开始,遍历到num[i]对应的树节点为止,所有路径上小于num[i]的节点的sum和dup之和即可,注意也要算上num[i]节点本身的sum
15-
* 因为num[i]本身可能有重复。
12+
* 建立一棵二叉树,从数组末尾开始遍历,这里每个树的节点要记录sum和dup
13+
* dup表示到当前为止,该节点重复的次数
14+
* sum表示该节点左子树中的节点总数,注意如果有的节点有重复也要算上。
15+
* 现在假如遍历到了数组中的第i个数,则其右边的所有数都已经生成了节点插到树中,
16+
* 此时我们只要统计从树的root开始,遍历到num[i]对应的树节点为止,所有路径上小于num[i]的节点的sum和dup之和即可,
17+
* 注意也要算上num[i]节点本身的sum
1618
*/
1719
public class CountOfSmallerNumbersAfterSelf {
1820

test/src/main/java/com/inuker/test/main.java

Lines changed: 47 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -31,30 +31,61 @@
3131
public class main {
3232

3333
public static void main(String[] args) {
34-
int[] arr = new int[]{
35-
4,3,2,7,8,2,3,1
36-
};
37-
for (int n : new FindAllNumbersDisappearedInAnArray().findDisappearedNumbers(arr)) {
34+
List<Integer> list = new test().countSmaller(new int[] {
35+
5, 2, 6, 1
36+
});
37+
for (Integer n : list) {
3838
System.out.print(n + " ");
3939
}
4040
}
4141

42-
public boolean wordBreak(String s, List<String> wordDict) {
43-
int n = s.length();
4442

45-
boolean[] dp = new boolean[n + 1];
46-
dp[0] = true;
43+
static class test {
44+
class Node {
45+
Node left, right;
46+
int val;
4747

48-
for (int i = 1; i < s.length(); i++) {
49-
for (String word: wordDict) {
50-
int j = i - word.length();
51-
if (j >= 0 && dp[j] && s.substring(j, i).equals(word)) {
52-
dp[i] = true;
53-
break;
54-
}
48+
/**
49+
* 左子树的节点个数
50+
*/
51+
int sum;
52+
53+
/**
54+
* 节点重复数
55+
*/
56+
int dup = 1;
57+
58+
public Node(int v, int s) {
59+
val = v;
60+
sum = s;
61+
}
62+
}
63+
64+
public List<Integer> countSmaller(int[] nums) {
65+
Node root = null;
66+
Integer[] res = new Integer[nums.length];
67+
for (int i = nums.length - 1; i >= 0; i--) {
68+
root = insert(root, nums[i], 0, res, i);
5569
}
70+
return Arrays.asList(res);
5671
}
5772

58-
return dp[n];
73+
private Node insert(Node root, int n, int pre, Integer[] res, int i) {
74+
if (root == null) {
75+
root = new Node(n, 0);
76+
res[i] = pre;
77+
} else if (root.val == n) {
78+
root.dup++;
79+
res[i] = pre + root.sum;
80+
} else if (n < root.val) {
81+
root.sum++;
82+
root.left = insert(root.left, n, pre, res, i);
83+
} else {
84+
root.right = insert(root.right, n, pre + root.sum + root.dup, res, i);
85+
}
86+
return root;
87+
}
5988
}
89+
90+
6091
}

0 commit comments

Comments
 (0)