力扣315.计算右侧小于当前元素的个数

力扣315.计算右侧小于当前元素的个数

  • 离散化 + 树状数组

cpp 复制代码
  const int N = 100010;
  int tr[N],n;
  class Solution {
  public:
      vector<int> countSmaller(vector<int>& nums) {
          n = nums.size();
          vector<int> tmp(nums);
          vector<int> res(n);
          memset(tr,0,sizeof tr);
          ranges::sort(tmp);
          int l = unique(tmp.begin(),tmp.end()) - tmp.begin();
          for(int i=0;i<n;i++)
              nums[i] = lower_bound(tmp.begin(),tmp.begin()+l,nums[i]) - tmp.begin() + 1;
          for(int i=n-1;i>=0;i--)
          {
              int val = nums[i];
              cout<<val<<" ";
              res[i] = query(val - 1);
              cout<<tr[1]<<endl;
              add(val,1);
          }
          return res;
      }
      int lowbit(int x)
      {
          return x&-x;
      }
      int query(int x) {
  		int ret = 0;
  		while (x) {
  			ret += tr[x];
  			x -= lowbit(x);
  		}
  		return ret;
  	}
      void add(int x, int k) {
  		while (x < n) {
  			tr[x] += k;
  			x += lowbit(x);
  		}
  	}
  };
相关推荐
文丑颜不良啊4 小时前
LeetCode1961~1980题目解析
java·leetcode
文丑颜不良啊4 小时前
LeetCode2001~2020题目解析
java·leetcode
文丑颜不良啊7 小时前
LeetCode2021~2040题目解析
java·leetcode
Nuanyt1 天前
LeetCode Hot 100 链表专题(五)· 2 题(Java)
java·算法·leetcode·链表
圣保罗的大教堂1 天前
leetcode 3736. 最小操作次数使数组元素相等 III 简单
leetcode
文丑颜不良啊1 天前
LeetCode1881~1990题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode1861~1880题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode1921~1940题目解析
java·leetcode
一去不复返的通信er1 天前
排序 + 双指针:力扣15三数之和
算法·leetcode