当前位置:网站首页>LeetCode 1200. Minimum absolute difference

LeetCode 1200. Minimum absolute difference

2022-07-05 06:10:00 Tisfy

【LetMeFly】1200. Minimum absolute difference

Force button topic link :https://leetcode.cn/problems/minimum-absolute-difference/

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]]

 

Tips :

  • 2 <= arr.length <= 10^5
  • -10^6 <= arr[i] <= 10^6

Method 1 : Sort

The data range of this question is 1 0 5 10^5 105, So it's impossible to O ( n 2 ) O(n^2) O(n2) violence

It's not hard , because After ordering “ The element pair with the smallest absolute difference ” It must be next to

So we can sort directly , Then traverse twice

For the first time, find the minimum value of only difference in absolute value , For the second time, the difference between the absolute values is equal to that of the minimum value pair Just put it in the answer .

  • Time complexity O ( n log ⁡ n ) O(n\log n) O(nlogn), among n n n It's an array arr \textit{arr} arr The length of
  • Spatial complexity O ( log ⁡ n ) O(\log n) O(logn), All are ordered

AC Code

C++

class Solution {
    
public:
    vector<vector<int>> minimumAbsDifference(vector<int>& arr) {
    
        sort(arr.begin(), arr.end());
        int m = arr[1] - arr[0];
        for (int i = 1; i < arr.size(); i++) {
    
            m = min(m, arr[i] - arr[i - 1]);
        }
        vector<vector<int>> ans;
        for (int i = 1; i < arr.size(); i++) {
    
            if (arr[i] - arr[i - 1] == m) {
    
                ans.push_back({
    arr[i - 1], arr[i]});
            }
        }
        return ans;
    }
};

Synchronous posting on CSDN, Originality is not easy. , Reprint please attach Link to the original text Oh ~
Tisfy:https://letmefly.blog.csdn.net/article/details/125609898

原网站

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