力扣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);
  		}
  	}
  };
相关推荐
_日拱一卒13 小时前
LeetCode:543二叉树的直径
算法·leetcode·职场和发展
穿条秋裤到处跑13 小时前
每日一道leetcode(2026.04.28):获取单值网格的最小操作数
算法·leetcode·职场和发展
leoufung13 小时前
LeetCode 68. Text Justification 题解:贪心与实现细节
算法·leetcode·职场和发展
洛水水14 小时前
【力扣100题】17.K 个一组翻转链表
算法·leetcode·链表
洛水水15 小时前
【力扣100题】16.两两交换链表中的节点
算法·leetcode·链表
leoufung15 小时前
LeetCode 30:Substring with Concatenation of All Words 题解(含 C 语言 uthash 实现)
c语言·leetcode·c#
样例过了就是过了15 小时前
LeetCode热题100 最小路径和
c++·算法·leetcode·动态规划
风筝在晴天搁浅17 小时前
LeetCode 143.重排链表
算法·leetcode·链表
承渊政道17 小时前
【动态规划算法】(子数组系列问题建模与解题思路精讲)
数据结构·c++·学习·算法·leetcode·动态规划·哈希算法
Morwit17 小时前
【力扣hot100】 494. 目标和
数据结构·算法·leetcode