🔗 🟢 1200. Minimum Absolute Difference

Problem Statement

題目簡述

給定由互不相同的整數組成的陣列 arr\textit{arr},找出所有絕對差等於「任意兩元素的最小絕對差」的元素對 [a,b][a, b],其中 a<ba < b。
回傳的元素對須按升序排列。

Constraints

約束條件

  • 2≤arr.length≤1052 \le \textit{arr.length} \le 10^5
  • −106≤arr[i]≤106-10^6 \le \textit{arr}[i] \le 10^6

思路:排序 + 相鄰比較

要讓兩個數的差最小,它們之間不該夾著其他數。若 a<c<ba < c < b,則 c−ac - a 與 b−cb - c 都嚴格小於 b−ab - a,所以 (a,b)(a, b) 一定不是最小差的元素對。

關鍵觀察

先 排序(Sorting) 之後,最小絕對差只會出現在相鄰元素之間,不必枚舉所有 O(n2)\mathcal{O}(n^2) 個元素對。

因此做法分兩步:

  1. 排序 arr\textit{arr},掃描所有相鄰元素對,得到最小差值 dd。
  2. 再掃描一次相鄰元素對,收集差值恰為 dd 的 [a,b][a, b]。

排序後元素對天然按 aa 由小到大出現,且題目保證元素互不相同,所以輸出自動符合升序的要求,不需要額外排序,也不會出現重複的元素對。

複雜度分析

  • 時間複雜度:O(nlog⁡n)\mathcal{O}(n \log n),其中 nn 為 arr\textit{arr} 的長度,瓶頸在排序,兩次相鄰掃描都是 O(n)\mathcal{O}(n)。
  • 空間複雜度:O(n)\mathcal{O}(n),排序的輔助空間,以及最壞情況(所有相鄰差都相同)下回傳的 n−1n - 1 個元素對。

Code

1
2
3
4
5
class Solution:
def minimumAbsDifference(self, arr: list[int]) -> list[list[int]]:
arr.sort()
min_diff = min(b - a for a, b in pairwise(arr))
return [[a, b] for a, b in pairwise(arr) if b - a == min_diff]

寫在最後

Cover Image Credit

The cover image was created by @月影暗霜. All rights belong to the original artist.

If you are the copyright holder and believe this usage is inappropriate, please contact me by email or leave a comment. I will remove the image promptly.