[Swift]LeetCode910. 最小差值 II | Smallest Range II
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10609971.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Given an array A
of integers, for each integer A[i]
we need to choose either x = -K
or x = K
, and add x
to A[i] (only once)
.
After this process, we have some array B
.
Return the smallest possible difference between the maximum value of B
and the minimum value of B
.
Example 1:
Input: A = [1], K = 0
Output: 0
Explanation: B = [1]
Example 2:
Input: A = [0,10], K = 2
Output: 6
Explanation: B = [2,8]
Example 3:
Input: A = [1,3,6], K = 3
Output: 3
Explanation: B = [4,6,3]
Note:
1 <= A.length <= 10000
0 <= A[i] <= 10000
0 <= K <= 10000
给定一个整数数组 A
,对于每个整数 A[i]
,我们可以选择 x = -K
或是 x = K
,并将 x
加到 A[i]
中。
在此过程之后,我们得到一些数组 B
。
返回 B
的最大值和 B
的最小值之间可能存在的最小差值。
示例 1:
输入:A = [1], K = 0 输出:0 解释:B = [1]
示例 2:
输入:A = [0,10], K = 2 输出:6 解释:B = [2,8]
示例 3:
输入:A = [1,3,6], K = 3 输出:3 解释:B = [4,6,3]
提示:
1 <= A.length <= 10000
0 <= A[i] <= 10000
0 <= K <= 10000
1 class Solution { 2 func smallestRangeII(_ A: [Int], _ K: Int) -> Int { 3 if A.count <= 1 { 4 return 0 5 } 6 let arr = A.sorted { (num1, num2) -> Bool in 7 return num1 < num2 8 } 9 let min1 = arr.first! + K 10 let max1 = arr.last! - K 11 var res = arr.last! - arr.first! 12 for i in 1 ..< arr.count { 13 let min2 = min(min1, arr[i] - K) 14 let max2 = max(max1, arr[i - 1] + K) 15 let temp = max2 - min2 16 res = temp > res ? res : temp 17 } 18 return res 19 } 20 }
164ms
1 class Solution { 2 func smallestRangeII(_ A: [Int], _ K: Int) -> Int { 3 var A = A.sorted() 4 if A.count == 0 || A.count == 1 { 5 return 0 6 } 7 if A[A.count - 1] - A[0] <= K { 8 return A[A.count - 1] - A[0] 9 } 10 var diff = A[A.count - 1] - A[0] 11 for i in 0..<(A.count - 1){ 12 let high = max(A[i] + 2 * K, A.last!) 13 let low = min(A[i + 1], A.first! + 2 * K) 14 diff = min(diff, high - low) 15 } 16 return diff 17 } 18 }
344ms
1 class Solution { 2 func smallestRangeII(_ A: [Int], _ K: Int) -> Int { 3 var A = A.sorted() 4 var n:Int = A.count 5 var mx:Int = A[n - 1] 6 var mn:Int = A[0] 7 var res:Int = mx - mn 8 for i in 0..<(n - 1) 9 { 10 mx = max(mx, A[i] + 2 * K) 11 mn = min(A[i + 1], A[0] + 2 * K) 12 res = min(res, mx - mn) 13 } 14 return res 15 } 16 }
392ms
1 class Solution { 2 func smallestRangeII(_ A: [Int], _ K: Int) -> Int { 3 var newA = Array(Set(A)).sorted() 4 let n = newA.count - 1 5 var min = newA[n] - newA[0] 6 if newA.count <= 1{ 7 return 0 8 } 9 for i in 1..<newA.count{ 10 var arr = [(newA[0]+K),(newA[i-1] + K),(newA[i] - K),(newA[n] - K)] 11 arr.sort() 12 let temp = arr.last! - arr.first! 13 if temp < min { 14 min = temp 15 } 16 } 17 return min 18 } 19 }