LintCode 248. Count of Smaller Number (线段树经典题!!)

  1. Count of Smaller Number
    中文English
    Give you an integer array (index from 0 to n-1, where n is the size of this array, value from 0 to 10000) and an query list. For each query, give you an integer, return the number of element in the array that are smaller than the given integer.

Example
Example 1:

Input: array =[1,2,7,8,5] queries =[1,8,5]
Output:[0,4,2]
Example 2:

Input: array =[3,4,5,8] queries =[2,4]
Output:[0,1]
Challenge
Could you use three ways to do it.

Just loop
Sort and binary search
Build Segment Tree and Search.
Notice
We suggest you finish problem Segment Tree Build and Segment Tree Query II first.

解法1:排序+Binary Search。排序预处理O(nlogn)。每次查询O(logn)。
注意:
1)当存在多个target时,Binary Search是找排序后数组中的第一个target。这样,返回的index刚好就是小于其的个数。
2)当target不在排序数组中时,Binary Search返回小于target的元素个数。
代码如下:

class Solution {
public:
    /**
     * @param A: An integer array
     * @param queries: The query list
     * @return: The number of element in the array that are smaller that the given integer
     */
    vector<int> countOfSmallerNumber(vector<int> &A, vector<int> &queries) {
        int n = A.size();
        int m = queries.size();
        if (m <= 0) return vector<int>();
        if (n <= 0) return vector<int>(m, 0);

        sort(A.begin(), A.end());
        
        vector<int> result;
        for (int i = 0; i < m; ++i) {
            result.push_back(findPos(A, queries[i]));
        }
        
        return result;
    }
    
private:
    int findPos(vector<int> &nums, int target) {
        int n = nums.size();
        int start = 0, end = n - 1;
        while(start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (nums[mid] >= target) {
                end = mid;
            } else if (nums[mid] < target) {
                start = mid;
            }
        }

        if (nums[end] == target) return end;   
        if (nums[end] < target) return end + 1;
        if (nums[start] == target) return start;
        if (nums[start] < target) return start + 1;
    }
};

2刷

class Solution {
public:
    /**
     * @param A: An integer array
     * @param queries: The query list
     * @return: The number of element in the array that are smaller that the given integer
     */
    vector<int> countOfSmallerNumber(vector<int> &A, vector<int> &queries) {
        int n = A.size();
        if (n == 0) return vector<int>(queries.size());
        map<int, int> num2Freq; //num, freq
        
        for (int i = 0; i < n; ++i) {
            num2Freq[A[i]]++;
        }

        vector<int> nums(num2Freq.size());
        int index = 0;
        for (auto a : num2Freq) {
            nums[index++] = a.first;
        }

        vector<int> preSums(nums.size());   //preSum[i] is the preSum of index2Num[i];
        preSums[0] = num2Freq[nums[0]];
        
        for (int i = 1; i < nums.size(); ++i) {
            preSums[i] = preSums[i - 1] + num2Freq[nums[i]];
        }

        vector<int> result;
        for (int i = 0; i < queries.size(); ++i) {
            int queryNum = queries[i];
            
            //find the closest index in nums[] that is smaller than queryNum
            int findIndex = -1;
            int start = 0, end = nums.size() - 1;
            while(start + 1 < end) {
                int mid = start + (end -start) / 2;
                if (nums[mid] < queryNum) {
                    start = mid;
                } else if (nums[mid] > queryNum) {
                    end = mid;
                } else {
                    //findIndex = mid;
                    end = mid;
                }
            }

            if (nums[start] == queryNum) findIndex = start - 1;
            if (nums[end] == queryNum) findIndex = end - 1;

            if (nums[end] < queryNum) findIndex = end;
            else if (nums[start] < queryNum) findIndex = start;

            if (findIndex == -1) 
                result.push_back(0);
            else 
                result.push_back(preSums[findIndex]);
        }
        
        return result;
    }
};

解法2:直接loop循环。每次用map查询。比较费时。
下次做。

解法3:线段树。预处理时间O(n),每次查询O(logn)。
代码如下:

struct SgMtTreeNode {
    int start, end, count;
    SgMtTreeNode *left, *right;
    SgMtTreeNode(int s = 0, int e = 0, int c = 0) : start(s), end(e), count(c) {
        left = nullptr;
        right = nullptr;
    } 
};

class Solution {
public:
    /**
     * @param A: An integer array
     * @param queries: The query list
     * @return: The number of element in the array that are smaller that the given integer
     */
    vector<int> countOfSmallerNumber(vector<int> &A, vector<int> &queries) {
        int n = A.size();
        int m = queries.size();
        if (n == 0) return vector<int>(m, 0);
        vector<int> result;
        SgMtTreeNode * root = build(0, 10000);
        for (auto i : A) {
            insert(root, i);
        }
        for (auto i : queries) {
            result.push_back(query(root, i - 1));   //note: i - 1
        }
        return result;
    }
    
private:
    SgMtTreeNode * build(int start, int end) {
        if (start > end) return nullptr;
        SgMtTreeNode * root = new SgMtTreeNode(start, end, 0);
        if (start == end) {
            return root;
        }
        int mid = start + (end - start) / 2;
        root->left = build(start, mid);
        root->right = build(mid + 1, end);
        return root;
    }
    
    //return the count that is smaller than target
    int query(SgMtTreeNode * root, int target) {
        if (!root) return 0;
        if (root->start > target) return 0;
        if (root->end <= target) return root->count;
        
        return query(root->left, target) + query(root->right, target);
    }
    
    void insert(SgMtTreeNode * root, int value) {
        if (!root) return;
        if (root->start == root->end) {
            root->count++;   //duplicate numbers!!
            return;
        }
        if (root->left && root->left->end >= value) {
            insert(root->left, value);
        } else if (root->right && root->right->start <= value) {
            insert(root->right, value);
        }
        root->count++;
    }
};

解法4:树状数组 TBD

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值