力扣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);
  		}
  	}
  };
相关推荐
怪兽学LLM6 小时前
LeetCode 21 合并两个有序链表:彻底理解虚拟头节点(Dummy)套路
python·leetcode·链表
_日拱一卒7 小时前
LeetCode:22括号生成
算法·leetcode·职场和发展
洛水水7 小时前
【力扣100题】88.多数元素
数据结构·算法·leetcode
洛水水8 小时前
【力扣100题】87.只出现一次的数字
数据结构·算法·leetcode
风筝在晴天搁浅9 小时前
LeetCode CodeTop 82.删除排序链表中的重复元素Ⅱ
算法·leetcode·链表
洛水水9 小时前
【力扣100题】84.字符串解码
算法·leetcode·职场和发展
洛水水9 小时前
【力扣100题】89.下一个排列
数据结构·算法·leetcode
洛水水9 小时前
【力扣100题】90.寻找重复数
算法·leetcode·职场和发展
alphaTao9 小时前
LeetCode 每日一题 2026/6/8-2026/6/14
算法·leetcode
想吃火锅100520 小时前
【leetcode】14.最长公共前缀js
算法·leetcode·职场和发展