Description
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]
.
Solution
Binary search, time O(n log n), space O(n)
这道题可以用Binary segment tree, Binary index tree, Binary search tree去解(which 我还不会写)。但是也可以用一个简简单单的二分查找来做。
从后向前遍历,同时维护一个已访问元素组成的sorted list,每次遍历到一个新元素是,在sorted list中查询其应该插入的位置,这个位置就是所求的smaller elements count。
class Solution {
public List<Integer> countSmaller(int[] nums) {
List<Integer> sorted = new ArrayList<>();
int n = nums.length;
Integer[] res = new Integer[n];
for (int i = n - 1; i >= 0; --i) {
int index = findInsertPos(sorted, nums[i]);
res[i] = index;
sorted.add(index, nums[i]);
}
return Arrays.asList(res);
}
public int findInsertPos(List<Integer> list, int target) {
int left = 0;
int right = list.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (list.get(mid) < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
}