★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-xlcixwsd-md.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i]and nums[j] is at most t and the absolute difference between i and j is at most k.git
Example 1:github
Input: nums = [1,2,3,1], k = 3, t = 0 Output: true
Example 2:數組
Input: nums = [1,0,1,1], k = 1, t = 2 Output: true
Example 3:微信
Input: nums = [1,5,9,1,5,9], k = 2, t = 3 Output: false
給定一個整數數組,判斷數組中是否有兩個不一樣的索引 i 和 j,使得 nums [i] 和 nums [j] 的差的絕對值最大爲 t,而且 i 和 j 之間的差的絕對值最大爲 ķ。spa
示例 1:code
輸入: nums = [1,2,3,1], k= 3, t = 0 輸出: true
示例 2:htm
輸入: nums = [1,0,1,1], k=1, t = 2 輸出: true
示例 3:blog
輸入: nums = [1,5,9,1,5,9], k = 2, t = 3 輸出: false
52ms
1 class Solution { 2 func containsNearbyAlmostDuplicate(_ nums: [Int], _ k: Int, _ t: Int) -> Bool { 3 var set: Set<Int> = [] 4 for (index, num) in nums.enumerated() { 5 if t == 0 { 6 if set.contains(num) { 7 return true 8 } 9 } else { 10 if set.contains(where: { abs($0 - num) <= t }) { 11 return true 12 } 13 } 14 15 set.insert(num) 16 17 if index >= k { 18 set.remove(nums[index - k]) 19 } 20 } 21 22 return false 23 } 24 }
60ms索引
1 class Solution { 2 func containsNearbyAlmostDuplicate(_ nums: [Int], _ k: Int, _ t: Int) -> Bool { 3 if nums.isEmpty || nums.count < 2 { 4 return false 5 } 6 var indices = [Int](0 ..< nums.count) 7 indices = indices.sorted(by: { a, b in nums[a] < nums[b] } ) 8 9 for i in 0 ..< nums.count { 10 var x = indices[i] 11 for j in (i + 1) ..< nums.count { 12 var y = indices[j] 13 var diffNums = nums[y] - nums[x] 14 var diffIndex = abs(x - y) 15 if diffNums > t { 16 break 17 } 18 if diffIndex <= k { 19 return true 20 } 21 } 22 } 23 return false 24 } 25 }
88ms
1 class Solution { 2 func containsNearbyAlmostDuplicate(_ nums: [Int], _ k: Int, _ t: Int) -> Bool { 3 if nums.count <= 1 || k < 1 || t < 0 { 4 return false 5 } 6 7 let mins = nums.min()! 8 var bucktes = [Int : Int]() 9 for i in 0..<nums.count { 10 if i > k { 11 let key = (nums[i-k-1] - mins) / (t+1) 12 bucktes.removeValue(forKey: key) 13 } 14 let key = (nums[i] - mins) / (t + 1) 15 if bucktes.keys.contains(key) { 16 return true 17 } 18 if let left = bucktes[key-1] , nums[i] - left <= t { 19 return true 20 } 21 if let right = bucktes[key+1], right - nums[i] <= t { 22 return true 23 } 24 bucktes[key] = nums[i] 25 } 26 27 return false 28 } 29 }