[LeetCode] 1200. Minimum Absolute Difference 最小絕對差



Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.

Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows

  • a, b are from arr
  • a < b
  • b - a equals to the minimum absolute difference of any two elements in arr

Example 1:

Input: arr = [4,2,1,3]
Output: [[1,2],[2,3],[3,4]]
Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.

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

Constraints:

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

這道題給了一個沒有重復數字的整型數組,現在讓找出差的絕對值最小的數對兒。既然是 Easy 的身價,那么就沒有太 Fancy 的解法,為了更方便的找出差的絕對值最小的數對兒,先給數組進行排序,這樣最小差值一定會出現在相鄰的兩個數字之間。接下來就是遍歷所有相鄰的兩個數字,維護一個最小值 mn,若當前差值 diff 小於等於 mn,則進行進一步操作,二者中唯一不同的是當 diff 小於 mn 時,結果 res 需要清空。然后將 mn 更新為 diff,並把當前數組對兒加入到結果 res 中即可,參見代碼如下:


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

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1200


參考資料:

https://leetcode.com/problems/minimum-absolute-difference/

https://leetcode.com/problems/minimum-absolute-difference/discuss/388289/Java-sorting-beats-100-explained


LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM