力扣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);
  		}
  	}
  };
相关推荐
Joyner20185 小时前
python-leetcode-从中序与后序遍历序列构造二叉树
算法·leetcode·职场和发展
因兹菜5 小时前
[LeetCode]day9 203.移除链表元素
算法·leetcode·链表
LNsupermali5 小时前
力扣257. 二叉树的所有路径(遍历思想解决)
算法·leetcode·职场和发展
雾月555 小时前
LeetCode LCR180文件组合
算法·leetcode·职场和发展
萌の鱼5 小时前
leetcode 2080. 区间内查询数字的频率
数据结构·c++·算法·leetcode
Tisfy5 小时前
LeetCode 0541.反转字符串 II:模拟
算法·leetcode·字符串·题解
labmem18 小时前
Leetcode:541
算法·leetcode·职场和发展
圆圆滚滚小企鹅。8 小时前
刷题记录 HOT100回溯算法-6:79. 单词搜索
笔记·python·算法·leetcode
钓一朵雪10 小时前
【Leetcode刷题记录】45. 跳跃游戏 II--贪心算法
leetcode·贪心算法
sjsjs1111 小时前
【数据结构-前缀树】力扣208. 实现 Trie (前缀树)
数据结构·leetcode