[LintCode] Count of Smaller Number before itself

Count of Smaller Number before itself

Give you an integer array (index from 0 to n-1, where n is the size of this array, value from 0 to 10000) . For each element Ai in the array, count the number of element before this element Ai is smaller than it and return count number array.

Example

For array [1,2,7,8,5], return [0,1,2,3,2]

Note

We suggest you finish problem Segment Tree BuildSegment Tree Query II and Count of Smaller Number before itself I first.

题目让用线段树,其实树状数组就能搞定,而且树状数组的代码太短小精悍了。

 1 class Solution {
 2 public:
 3    /**
 4      * @param A: An integer array
 5      * @return: Count the number of element before this element 'ai' is 
 6      *          smaller than it and return count number array
 7      */
 8     int lowbit(int n) {
 9         return n & (-n);
10     }
11     
12     int sum(vector<int> &c, int n) {
13         int sum = 0;
14         while (n > 0) {
15             sum += c[n];
16             n -= lowbit(n);
17         }
18         return sum;
19     }
20     
21     void add(vector<int> &c, int i, int x) {
22         while (i < c.size()) {
23             c[i] += x;
24             i += lowbit(i);
25         }
26     }
27     
28     vector<int> countOfSmallerNumberII(vector<int> &A) {
29         // write your code here
30         vector<int> c(10002, 0);
31         vector<int> res(A.size());
32         for (int i = 0; i < A.size(); ++i) {
33             res[i] = sum(c, A[i]);
34             add(c, A[i] + 1, 1);
35         }
36         return res;
37     }
38 };

如果有负数或者数特别大的话,可以先离散化一下再搞。

 1 class Solution {
 2 public:
 3    /**
 4      * @param A: An integer array
 5      * @return: Count the number of element before this element 'ai' is 
 6      *          smaller than it and return count number array
 7      */
 8     int lowbit(int n) {
 9         return n & (-n);
10     }
11     
12     int sum(vector<int> &c, int n) {
13         int sum = 0;
14         while (n > 0) {
15             sum += c[n];
16             n -= lowbit(n);
17         }
18         return sum;
19     }
20     
21     void add(vector<int> &c, int i, int x) {
22         while (i < c.size()) {
23             c[i] += x;
24             i += lowbit(i);
25         }
26     }
27     
28     vector<int> countOfSmallerNumberII(vector<int> &A) {
29         // write your code here
30         vector<int> c(A.size() + 1, 0);
31         vector<int> res(A.size()), B(A);
32         map<int, int> mp;
33         sort(B.begin(), B.end());
34         for (int i = 0; i < B.size(); ++i) {
35             mp[B[i]] = i + 1;
36         }
37         for (int i = 0; i < A.size(); ++i) {
38             res[i] = sum(c, mp[A[i]] - 1);
39             add(c, mp[A[i]], 1);
40         }
41         return res;
42     }
43 };
原文地址:https://www.cnblogs.com/easonliu/p/4575645.html