leetcode315 Count of Smaller Numbers After Self
发布时间:2020-12-14 04:47:59 所属栏目:大数据 来源:网络整理
导读:思路: bit + 离散化。 实现: 1 #include bits/stdc++.h 2 using namespace std; 3 class Solution 4 { 5 public : 6 int sum(vector int bit, int i) 7 { 8 int ans = 0 ; 9 while (i) { ans += bit[i]; i -= i - i; } 10 return ans; 11 } 12 void add(ve
思路: bit + 离散化。 实现: 1 #include <bits/stdc++.h> 2 using namespace std; 3 class Solution 4 { 5 public: 6 int sum(vector<int> & bit,int i) 7 { 8 int ans = 0; 9 while (i) { ans += bit[i]; i -= i & -i; } 10 return ans; 11 } 12 void add(vector<int> & bit,int i,int x) 13 { 14 int n = bit.size() - 1; 15 while (i <= n) { bit[i] += x; i += i & -i; } 16 } 17 vector<int> countSmaller(vector<int>& nums) 18 { 19 int n = nums.size(); 20 vector<int> a(nums.begin(),nums.end()),b(nums.begin(),nums.end()); 21 sort(a.begin(),a.end()); 22 a.erase(unique(a.begin(),a.end()),a.end()); 23 for (int i = 0; i < n; i++) 24 b[i] = lower_bound(a.begin(),a.end(),b[i]) - a.begin() + 1; 25 vector<int> bit(n + 1,0),ans(n,0); 26 for (int i = n - 1; i >= 0; i--) 27 { 28 add(bit,b[i],1); 29 ans[i] = b[i] == 1 ? 0 : sum(bit,b[i] - 1); 30 } 31 return ans; 32 } 33 }; 34 int main() 35 { 36 vector<int> v; 37 v.push_back(5); 38 v.push_back(-1); 39 v.push_back(6); 40 v.push_back(1); 41 vector<int> ans = Solution().countSmaller(v); 42 for (auto it: ans) cout << it << " "; 43 cout << endl; 44 return 0; 45 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |