556.Find the Smallest Difference Between Any Two Values
Easy
Given an array
nums with at least two values, return the smallest absolute difference between any two of them.
Sorting is the classic O(n log n)Linearithmic Time O(n log n)The cost of efficient sorting: a little more than linear, far less than quadratic. operation, and it often turns a hard question into an easy one. Checking every pair is O(n²); after sorting, only neighbours can be closest, so a single O(n) scan finishes the job. The sort's O(n log n) dominates the total.
Example 1:
Input: nums = [30,5,20,9]
Output: 4
Example 2:
Input: nums = [8,3,8]
Output: 0
+ 5 hidden test cases run on Submit.
Constraints:
- ●
2 ≤ nums.length ≤ 1000 - ●
-1000000 ≤ nums[i] ≤ 1000000
nums =
[30, 5, 20, 9]