力扣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);
  		}
  	}
  };
相关推荐
tachibana22 小时前
hot100 回文链表(234)
java·网络·数据结构·leetcode·链表
wabs6664 小时前
关于动态规划【力扣1143.最长公共子序列的思考】
算法·leetcode·动态规划
剑挑星河月5 小时前
54.螺旋矩阵
java·算法·leetcode·矩阵
笨笨没好名字6 小时前
Leetcode刷题python3版第一周(下)
linux·算法·leetcode
青山木8 小时前
Hot 100 --- LRU 缓存
java·数据结构·算法·leetcode·链表·缓存·哈希
想你依然心痛9 小时前
AtomCode在算法竞赛中的实战体验:LeetCode周赛辅助编程
linux·算法·leetcode
剑挑星河月10 小时前
35.搜索插入位置
java·数据结构·算法·leetcode
闪电悠米10 小时前
力扣hot100-438.找到字符串中所有字母异位词-固定长度滑动窗口详解
linux·服务器·数据结构·算法·leetcode·滑动窗口·力扣hot100
小陈的代码之路1 天前
回文链表(LeetCode 234)C语言最佳解题思路
c语言·leetcode·链表
郭梧悠1 天前
算法:有效的括号
python·算法·leetcode