力扣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);
  		}
  	}
  };
相关推荐
北顾笙9809 分钟前
day22-数据结构力扣
数据结构·算法·leetcode
人道领域15 分钟前
【LeetCode刷题日记】454:四数相加Ⅱ
算法·leetcode
进击的荆棘1 小时前
递归、搜索与回溯——递归
算法·leetcode·递归
小白菜又菜12 小时前
Leetcode 2075. Decode the Slanted Ciphertext
算法·leetcode·职场和发展
摸个小yu16 小时前
【力扣LeetCode热题h100】链表、二叉树
算法·leetcode·链表
skywalker_1117 小时前
力扣hot100-5(盛最多水的容器),6(三数之和)
算法·leetcode·职场和发展
生信研究猿17 小时前
leetcode 226.翻转二叉树
算法·leetcode·职场和发展
XWalnut18 小时前
LeetCode刷题 day9
java·算法·leetcode
6Hzlia18 小时前
【Hot 100 刷题计划】 LeetCode 39. 组合总和 | C++ 回溯算法与 startIndex 剪枝
c++·算法·leetcode
宵时待雨18 小时前
优选算法专题1:双指针
数据结构·c++·笔记·算法·leetcode