力扣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);
  		}
  	}
  };
相关推荐
小年糕是糕手12 小时前
【C++】C++入门 -- 输入&输出、缺省参数
c语言·开发语言·数据结构·c++·算法·leetcode·排序算法
程序猿小白日记13 小时前
走向智能化:从编程语言看人工智能的未来
leetcode
天选之女wow16 小时前
【Hard——Day8】65.有效数字、68.文本左右对齐、76.最小覆盖子串
linux·运维·redis·算法·leetcode
2501_9418008817 小时前
5G技术引领下的智能制造革命:如何推动工业4.0发展
leetcode
小白程序员成长日记17 小时前
2025.11.21 力扣每日一题
算法·leetcode·职场和发展
sin_hielo19 小时前
leetcode 1930
算法·leetcode
努力学算法的蒟蒻21 小时前
day17(11.18)——leetcode面试经典150
算法·leetcode·面试
不爱编程爱睡觉21 小时前
代码随想录算法训练营第二十八天 | 动态规划算法基础、 LeetCode509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯
算法·leetcode·动态规划·代码随想录
yagamiraito_1 天前
757. 设置交集大小至少为2 (leetcode每日一题)
算法·leetcode·go
无敌最俊朗@1 天前
力扣hot100-141.环形链表
算法·leetcode·链表