力扣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);
  		}
  	}
  };
相关推荐
水木流年追梦1 小时前
大模型入门-Reward 奖励模型训练
开发语言·python·算法·leetcode·正则表达式
始三角龙8 小时前
LeetCode hoot 100 -- 缺失的第一个正整数
算法·leetcode·职场和发展
战南诚10 小时前
力扣 之 198.打家劫舍
python·算法·leetcode
_日拱一卒11 小时前
LeetCode:105从前序与中序遍历序列构造二叉树
算法·leetcode·职场和发展
ʚ希希ɞ ྀ12 小时前
dp反思与总结
算法·leetcode·动态规划
菜菜的顾清寒12 小时前
力扣Hot100(23)反转链表
算法·leetcode·链表
m0_6294947312 小时前
LeetCode 热题 100-----27. 合并两个有序链表
数据结构·算法·leetcode·链表
水木流年追梦12 小时前
大模型入门-RL基础
开发语言·python·算法·leetcode·正则表达式
人道领域12 小时前
【LeetCode刷题日记】617.合并二叉树(空间换安全,还是原地省内存)
java·数据结构·算法·leetcode
运筹vivo@12 小时前
3043. 最长公共前缀的长度(Leetcode 每日一题)
c++·算法·leetcode·职场和发展·每日一题