【Leetcode】Count of Smaller Numbers After Self
來源:程序員人生 發布時間:2016-06-20 17:00:05 閱讀次數:2574次
題目鏈接:https://leetcode.com/problems/count-of-smaller-numbers-after-self/
題目:
You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i]
is
the number of smaller elements to the right of nums[i]
.
Example:
Given nums = [5, 2, 6, 1]
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.
Return the array [2, 1, 1, 0]
.
思路:
建立1個2叉搜索樹,在建樹的進程中,記錄在數組右側比本身小的元素個數。 算法復雜度O(nlogn),用動態計劃復雜度為O(n^2)。
其中cnt為該結點相同大小元素的個數,用于重復元素判斷。。。其實可以省略。。懶得改了
算法:
public List<Integer> countSmaller(int[] nums) {
List<Integer> list = new ArrayList<Integer>();
int res[] = new int[nums.length];
for (int i = nums.length - 1; i >= 0; i--) {
res[i] = insert(nums[i]);
}
for (int i : res) {
list.add(i);
}
return list;
}
TreeNode tRoot;
private Integer insert(int val) {
int cnt = 0;
if (tRoot == null) {
tRoot = new TreeNode(val);
return cnt;
}
TreeNode root = tRoot;
while (root != null) {
if (val < root.val) {
root.leftCnt++;
if (root.left == null) {
root.left = new TreeNode(val);
break;
} else
root = root.left;
} else if (val > root.val) {
cnt += root.leftCnt + root.cnt;
if (root.right == null) {
root.right = new TreeNode(val);
break;
} else
root = root.right;
} else {
cnt += root.leftCnt;
root.cnt++;
break;
}
}
return cnt;
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈