力扣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);
  		}
  	}
  };
相关推荐
OpenC++28 分钟前
【C++QT】Layout 布局管理控件详解
c++·经验分享·qt·leetcode
1白天的黑夜11 小时前
贪心算法-860.柠檬水找零-力扣(LeetCode)
c++·算法·leetcode·贪心算法
Y1nhl2 小时前
力扣hot100_子串_python版本
开发语言·python·算法·leetcode·职场和发展
共享家952716 小时前
栈相关算法题解题思路与代码实现分享
c++·leetcode
Wendy_robot16 小时前
【前缀和计算和+哈希表查找次数】Leetcode 560. 和为 K 的子数组
c++·算法·leetcode
o独酌o16 小时前
算法习题-力扣446周赛题解
算法·leetcode
云格~17 小时前
Leetcode:1. 两数之和
数据结构·算法·leetcode
xxjiaz17 小时前
水果成篮--LeetCode
java·算法·leetcode·职场和发展
肥or胖17 小时前
【LeetCode 热题 100】链表 系列
算法·leetcode·链表