jinxuan
7/10/2015 - 5:35 AM

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;
    }
};