c_cpp http://www.lintcode.com/en/problem/count-of-smaller-number/

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp http://www.lintcode.com/en/problem/count-of-smaller-number/相关的知识,希望对你有一定的参考价值。

class Solution {
    public:
    /**
    * @param A: An integer array
    * @return: The number of element in the array that
    *          are smaller that the given integer
    */
    //binary search, return closest larger.
    
    //a binary search that find the closet index smaller than the query value.
    
  int binarySearch(vector<int> A, int query, int begin, int end) {
	if (end < 0) {
		return 0;
	}
	int mid = 0;
	while (end > begin) {
		mid = begin + (end - begin) / 2;
		//Since in the test case there exists duplicate elements, we need to move left until we find the first one not equal to the query value.
		if (A[mid] == query){
		    int tmp = mid;
		    while(A[tmp] == A[mid]){
		        tmp--;
		    }
		    //move 1 back
			return ++tmp;
		}
		if (A[mid] > query) {
			end = mid;
		}
		else if (A[mid] < query) {
			begin = mid + 1;
		}
	}
    //this "begin" indicate the closest one to the query value. we need to make sure it is not larger than the query value.
    int diff = A[begin] - query;
	if(diff > 0)
	    return end;
	else
	    return end - 1;
    }
    vector<int> countOfSmallerNumber(vector<int> &A, vector<int> &queries) {
        // write your code here
        std:sort(A.begin(), A.end());
        
        //binary search;
        vector<int> result;
        for(int i = 0; i < queries.size(); i++) {
            int position = binarySearch(A, queries[i], 0, A.size() - 1);
            result.push_back(position);
        }
        return result;
    }
};

以上是关于c_cpp http://www.lintcode.com/en/problem/count-of-smaller-number/的主要内容,如果未能解决你的问题,请参考以下文章

LintCode Triangle Count

LintCode Longest Common Subsequence

[LintCode] Graph Valid Tree

LintCode:剑指Offer

Lintcode15 Permutations solution 题解

LintCode Longest Common Substring