力扣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);
  		}
  	}
  };
相关推荐
哎写bug的程序员3 小时前
leetcode复盘(1)
算法·leetcode·职场和发展
qq_534452525 小时前
【算法 day02】LeetCode 209.长度最小的子数组 | 59.螺旋矩阵II
java·算法·leetcode·职场和发展
dying_man5 小时前
LeetCode--31.下一个排列
算法·leetcode
IC 见路不走5 小时前
LeetCode 第75题:颜色分类
数据结构·算法·leetcode
Navigator_Z6 小时前
LeetCode //C - 757. Set Intersection Size At Least Two
c语言·算法·leetcode
GalaxyPokemon15 小时前
LeetCode - 704. 二分查找
数据结构·算法·leetcode
liuqun031919 小时前
开心灿烂go开发面试题
算法·leetcode·golang
এ᭄画画的北北19 小时前
力扣-279.完全平方数
数据结构·算法·leetcode
GalaxyPokemon20 小时前
LeetCode - LCR 173. 点名
算法·leetcode·职场和发展
爱coding的橙子1 天前
每日算法刷题Day31 6.14:leetcode二分答案2道题,结束二分答案,开始枚举技巧,用时1h10min
算法·leetcode·职场和发展