★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-xlauxxwz-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★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)
.git
After this process, we have some array B
.github
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:this
Input: A = [0,10], K = 2 Output: 6 Explanation: B = [2,8]
Example 3:spa
Input: A = [1,3,6], K = 3 Output: 3 Explanation: B = [4,6,3]
Note:code
1 <= A.length <= 10000
0 <= A[i] <= 10000
0 <= K <= 10000
給定一個整數數組 A
,對於每一個整數 A[i]
,咱們能夠選擇 x = -K
或是 x = K
,並將 x
加到 A[i]
中。htm
在此過程以後,咱們獲得一些數組 B
。blog
返回 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 }