Closest Numbers

  • + 0 comments

    c++ solution

    vector<int> closestNumbers(vector<int> arr) {
        vector<int>result;
        // minimun difference
        int mini=INT_MAX;
        sort(arr.begin(),arr.end());
        for(int i=0;i<arr.size()-1;i++){
            
            int absDiff=abs(arr[i]-arr[i+1]);
            if(absDiff<mini){
                mini=absDiff;
                result.erase(result.begin(),result.end());
                result.push_back(arr[i]);
                result.push_back(arr[i+1]);
            }
            else if(absDiff==mini){
                 result.push_back(arr[i]);
                result.push_back(arr[i+1]);
            }
        }
        return result;
        
    }