力扣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);
  		}
  	}
  };
相关推荐
好易学·数据结构4 小时前
可视化图解算法57:字符串的排列
数据结构·算法·leetcode·面试·笔试·回溯算法·牛客
এ᭄画画的北北6 小时前
力扣-283.移动零
算法·leetcode
墨染点香14 小时前
LeetCode 刷题【31. 下一个排列】
算法·leetcode·职场和发展
wrynhyxa14 小时前
力扣热题100——子串
算法·leetcode·哈希算法
Q741_14716 小时前
优选算法 力扣 611. 有效三角形的个数 双指针降低时间复杂度 贪心策略 C++题解 每日一题
c++·算法·leetcode·贪心·双指针
想要AC的sjh16 小时前
【Leetcode】904. 水果成篮
算法·leetcode·职场和发展
এ᭄画画的北北17 小时前
力扣-49.字母异位词分组
算法·leetcode
设计师小聂!17 小时前
力扣热题100-------169.多数元素
java·数据结构·算法·leetcode·多数元素
17 小时前
LeetCode Hot 100 买卖股票的最佳时机
算法·leetcode·职场和发展
蒟蒻小袁18 小时前
力扣面试150题--加一
算法·leetcode·职场和发展