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]
.
题目意思:给出一个数组你需要返回后面的数比数组里各自的数小的个数,组成一个count数组 ,例子上面有。
解题思路:暴力解法就是来两个for循环,第二个循环从当前下标的下一个开始与其当前比较遍历,但是这样的话,时间复杂度是O(n2),会超时不通过leetCode;另一种想法是这样:用vector去储存一对pair<int value,int postion>,pair里左边是数组中值,第二个是值对应的下标。采用分治->合并的方法去计算每次两两合并后当前合并后数组的position位置对应比较的count是多少,接着递归到下一个归并过程中。
1 #include <stdio.h> 2 3 #include <vector> 4 class Solution { 5 public: 6 std::vector<int> countSmaller(std::vector<int>& nums) { 7 std::vector<std::pair<int, int> > vec; 8 std::vector<int> count; 9 for (int i = 0; i < nums.size(); i++){ 10 vec.push_back(std::make_pair(nums[i], i)); 11 count.push_back(0); 12 } 13 merge_sort(vec, count); 14 return count; 15 } 16 private: 17 void merge_sort_two_vec( 18 std::vector<std::pair<int, int> > &sub_vec1, 19 std::vector<std::pair<int, int> > &sub_vec2, 20 std::vector<std::pair<int, int> > &vec, 21 std::vector<int> &count){ 22 int i = 0; 23 int j = 0; 24 while(i < sub_vec1.size() && j < sub_vec2.size()){ 25 if (sub_vec1[i].first <= sub_vec2[j].first){ 26 count[sub_vec1[i].second] += j; 27 vec.push_back(sub_vec1[i]); 28 i++; 29 } 30 else{ 31 vec.push_back(sub_vec2[j]); 32 j++; 33 } 34 } 35 for (; i < sub_vec1.size(); i++){ 36 count[sub_vec1[i].second] += j; 37 vec.push_back(sub_vec1[i]); 38 } 39 for (; j < sub_vec2.size(); j++){ 40 vec.push_back(sub_vec2[j]); 41 } 42 } 43 void merge_sort(std::vector<std::pair<int, int> > &vec, 44 std::vector<int> &count){ 45 if (vec.size() < 2){ 46 return; 47 } 48 int mid = vec.size() / 2; 49 std::vector<std::pair<int, int> > sub_vec1; 50 std::vector<std::pair<int, int> > sub_vec2; 51 for (int i = 0; i < mid; i++){ 52 sub_vec1.push_back(vec[i]); 53 } 54 for (int i = mid; i < vec.size(); i++){ 55 sub_vec2.push_back(vec[i]); 56 } 57 merge_sort(sub_vec1, count); 58 merge_sort(sub_vec2, count); 59 vec.clear(); 60 merge_sort_two_vec(sub_vec1, sub_vec2, vec, count); 61 } 62 }; 63 64 int main(){ 65 int test[] = {5, -7, 9, 1, 3, 5, -2, 1}; 66 std::vector<int> nums; 67 for (int i = 0; i < 8; i++){ 68 nums.push_back(test[i]); 69 } 70 Solution solve; 71 std::vector<int> result = solve.countSmaller(nums); 72 for (int i = 0; i < result.size(); i++){ 73 printf("[%d]", result[i]); 74 } 75 printf("\n"); 76 return 0; 77 }
通过~