Find the closest number of K in the sorted array

Posted by Cantaloupe on Tue, 08 Oct 2019 02:13:30 +0200

Give a target number, a non-negative integer k, an array A in ascending order. Find K integers closest to target in A. Return the number of K and rank it from small to large according to the degree of proximity to target. If the degree of proximity is the same, then the small number ranks first.

Example

Sample 1:

Input: A = 1, 2, 3], target = 2, k = 3
 Output: [2, 1, 3]

Sample 2:

Input: A = 1, 4, 6, 8], target = 3, k = 3
 Output: [4, 1, 6]

Challenge

Time complexity of O(logn + k)

Matters needing attention

  1. k is a non-negative integer and is always less than the length of the sorted array.
  2. The length of a given array is a positive integer and will not exceed 10 ^ 410 4.
  3. The absolute value of elements in an array will not exceed 10^410 4.

How does input test data (one parameter per row) understand test data?

 

bool cmp(pair<int, int> a, pair<int, int> b) 
{
    if(a.second < b.second)
        return true;
    else if(a.second > b.second)
        return false;
    if(a.first < b.first)
        return true;
    return false;
	
}



class Solution {
public:
    /**
     * @param A: an integer array
     * @param target: An integer
     * @param k: An integer
     * @return: an integer array
     */
    vector<int> kClosestNumbers(vector<int> &A, int target, int k) 
    {
        // write your code here
        vector<int> ret;
        if(k == 0)
            return ret;
        unordered_map<int, int> mymap;
        int size = A.size();
        for(int i = 0; i < size; i++)
        {
            mymap[A[i]] = abs(A[i] - target);
        }
        
        vector<pair<int, int>> vc;
        for(auto mit=mymap.begin(); mit!=mymap.end(); mit++)
        {
    		vc.push_back(pair<int, int>(mit->first, mit->second));
        }
        
        sort(vc.begin(), vc.end(), cmp);
        //int count = 0;
        for(auto vit=vc.begin(); vit!=vc.end(); vit++) 
        {
		    //cout<<vit->first<<"  "<<vit->second<<endl;
		    ret.push_back(vit->first);
            if(ret.size() == k)
                break;
        }
    
        return ret;
    }
};

 

Topics: less