• 力扣(LeetCode)315. 计算右侧小于当前元素的个数(2022.11.12)


    给你一个整数数组 nums ,按要求返回一个新数组 counts 。数组 counts 有该性质: counts[i] 的值是 nums[i] 右侧小于 nums[i] 的元素的数量。

    示例 1:

    输入:nums = [5,2,6,1]
    输出:[2,1,1,0]
    解释:
    5 的右侧有 2 个更小的元素 (2 和 1)
    2 的右侧仅有 1 个更小的元素 (1)
    6 的右侧有 1 个更小的元素 (1)
    1 的右侧有 0 个更小的元素

    示例 2:

    输入:nums = [-1]
    输出:[0]
    示例 3:

    输入:nums = [-1,-1]
    输出:[0,0]

    提示:

    1 <= nums.length <= 105
    -104 <= nums[i] <= 104

    来源:力扣(LeetCode)
    链接:https://leetcode.cn/problems/count-of-smaller-numbers-after-self

    方法一:离散化树状数组

    C++提交内容:

    class Solution {
    private:
        vector<int> c;
        vector<int> a;
    
        void Init(int length) {
            c.resize(length, 0);
        }
    
        int LowBit(int x) {
            return x & (-x);
        }
    
        void Update(int pos) {
            while (pos < c.size()) {
                c[pos] += 1;
                pos += LowBit(pos);
            }
        }
    
        int Query(int pos) {
            int ret = 0;
    
            while (pos > 0) {
                ret += c[pos];
                pos -= LowBit(pos);
            }
    
            return ret;
        }
    
        void Discretization(vector<int>& nums) {
            a.assign(nums.begin(), nums.end());
            sort(a.begin(), a.end());
            a.erase(unique(a.begin(), a.end()), a.end());
        }
        
        int getId(int x) {
            return lower_bound(a.begin(), a.end(), x) - a.begin() + 1;
        }
    public:
        vector<int> countSmaller(vector<int>& nums) {
            vector<int> resultList;
    
            Discretization(nums);
    
            Init(nums.size() + 5);
            
            for (int i = (int)nums.size() - 1; i >= 0; --i) {
                int id = getId(nums[i]);
                resultList.push_back(Query(id - 1));
                Update(id);
            }
    
            reverse(resultList.begin(), resultList.end());
    
            return resultList;
        }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
  • 相关阅读:
    Java 系语言测试覆盖率的半个解决方案
    CleanMyMac是什么软件?有哪些特色功能?
    react&antd问题
    vue-element-admin 综合开发五:引入 echarts,封装echarts 组件
    Helm3模板-其他注意事项
    C++设计模式之外观模式(结构型模式)
    Go语言常用命令详解(三)
    Redis面试题(四)
    自主实现HTTP服务器项目逻辑
    PyTorch 中的乘法:mul()、multiply()、matmul()、mm()、mv()、dot()
  • 原文地址:https://blog.csdn.net/ChaoYue_miku/article/details/127827439