力扣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);
  		}
  	}
  };
相关推荐
POLITE312 小时前
Leetcode 23. 合并 K 个升序链表 (Day 12)
算法·leetcode·链表
会员果汁13 小时前
leetcode-动态规划-买卖股票
算法·leetcode·动态规划
橘颂TA14 小时前
【剑斩OFFER】算法的暴力美学——二进制求和
算法·leetcode·哈希算法·散列表·结构与算法
尋有緣16 小时前
力扣1355-活动参与者
大数据·数据库·leetcode·oracle·数据库开发
Morwit17 小时前
*【力扣hot100】 647. 回文子串
c++·算法·leetcode
菜鸟233号18 小时前
力扣96 不同的二叉搜索树 java实现
java·数据结构·算法·leetcode
千金裘换酒18 小时前
Leetcode 有效括号 栈
算法·leetcode·职场和发展
空空潍19 小时前
hot100-最小覆盖字串(day12)
数据结构·算法·leetcode
POLITE31 天前
Leetcode 142.环形链表 II JavaScript (Day 10)
javascript·leetcode·链表
千金裘换酒1 天前
Leetcode 二叉树中序遍历 前序遍历 后序遍历(递归)
算法·leetcode·职场和发展