当前位置:网站首页>Leetcode-1200: minimum absolute difference

Leetcode-1200: minimum absolute difference

2022-07-05 06:09:00 Chrysanthemum headed bat

leetcode-1200: Minimum absolute difference

subject

Topic linking

Here's an array of integers arr, Each of these elements is inequality .

Please find all the elements with the least absolute difference , And return in ascending order .

Example 1:

 Input :arr = [4,2,1,3]
 Output :[[1,2],[2,3],[3,4]]

Example 2:

 Input :arr = [1,3,6,10,15]
 Output :[[1,3]]

Example 3:

 Input :arr = [3,8,-10,23,19,-4,-14,27]
 Output :[[-14,-10],[19,23],[23,27]]

Problem solving

Method 1 : Sort + One traverse

class Solution {
    
public:
    vector<vector<int>> minimumAbsDifference(vector<int>& arr) {
    
        sort(arr.begin(),arr.end());
        vector<vector<int>> res;
        int minDistance=INT_MAX;
        for(int i=1;i<arr.size();i++){
    
            int distance=arr[i]-arr[i-1];
            if(distance<minDistance){
    
                minDistance=distance;
                res.clear();
                res.push_back({
    arr[i-1],arr[i]});
            }
            else if(distance==minDistance){
    
                res.push_back({
    arr[i-1],arr[i]});
            }
        }
        return res;
    }
};
原网站

版权声明
本文为[Chrysanthemum headed bat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050546085439.html