315. 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]
.
solution:
class Solution {
2
public:
3
void divide(vector<int>& nums, vector<int>& ans, vector<int>& d, vector<vector<int> >& temp, int start, int end) {
4
if (start == end) return;
5
divide(nums, ans, d, temp, start, (start+end)/2);
6
divide(nums, ans, d, temp, (start+end)/2+1, end);
7
int i = start, j = (start+end)/2+1, k = start;
8
while (i <= (start+end)/2 || j <= end) {
9
if (i == (start+end)/2+1) j++;
10
else if (j == end+1) i++;
11
else if (nums[i] > nums[j]) {
12
ans[i] += end-j+1;
13
i++;
14
} else j++;
15
}
16
i = start, j = (start+end)/2+1;
17
while (i <= (start+end)/2 || j <= end) {
18
if (i == (start+end)/2+1) {
19
temp[0][k] = nums[j]; temp[1][k] = ans[j]; temp[2][k] = d[j];
20
k++; j++;
21
} else if (j == end+1) {
22
temp[0][k] = nums[i]; temp[1][k] = ans[i]; temp[2][k] = d[i];
23
k++; i++;
24
} else if (nums[i] > nums[j]) {
25
temp[0][k] = nums[i]; temp[1][k] = ans[i]; temp[2][k] = d[i];
26
k++; i++;
27
} else {
28
temp[0][k] = nums[j]; temp[1][k] = ans[j]; temp[2][k] = d[j];
29
k++; j++;
30
}
31
}
32
for (int l = start; l <= end; l++) {
33
nums[l] = temp[0][l]; ans[l] = temp[1][l]; d[l] = temp[2][l];
34
}
35
}
36
vector<int> countSmaller(vector<int>& nums) {
37
vector<int> ans, d, final, no;
38
vector<vector<int> > temp;
39
if (nums.size() == 0) return ans;
40
temp.push_back(no); temp.push_back(no); temp.push_back(no);
41
for (int i = 0; i < nums.size(); i++) {
42
ans.push_back(0); d.push_back(i); final.push_back(0);
43
temp[0].push_back(0); temp[1].push_back(0); temp[2].push_back(0);
44
}
45
divide(nums, ans, d, temp, 0, nums.size()-1);
46
for (int i = 0; i < nums.size(); i++) final[d[i]] = ans[i];
47
return final;
48
}
49
};