Count of Smaller Numbers After Self

来源:互联网 发布:mysql多group by 编辑:程序博客网 时间:2024/06/05 08:22

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].

解析:

从右向左遍历,对于每个新元素,把他插入到一个排序的数组中,它的位置就是右边比他小的元素的个数。

代码:

class Solution {public:    vector<int> countSmaller(vector<int>& nums) {        vector<int>ans(nums.size(),0);        vector<int>tt;        for (int i=nums.size()-1; i>=0; i--)        {            int left=0;            int right=tt.size();            while (left<right)            {                int mid=(left+right)/2;                                if (nums[i]<=tt[mid]) right=mid;                else                left=mid+1;            }                        tt.insert(tt.begin()+right,nums[i]);            ans[i]=right;        }                return ans;            }};


0 0
原创粉丝点击