★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-gjvlfmky-md.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.git
Example 1:github
Input: nums = [1,2,3,1], k = 3 Output: true
Example 2:數組
Input: nums = [1,0,1,1], k = 1 Output: true
Example 3:微信
Input: nums = [1,2,3,1,2,3], k = 2 Output: false
給定一個整數數組和一個整數 k,判斷數組中是否存在兩個不一樣的索引 i 和 j,使得 nums [i] = nums [j],而且 i 和 j 的差的絕對值最大爲 k。spa
示例 1:code
輸入: nums = [1,2,3,1], k= 3 輸出: true
示例 2:htm
輸入: nums = [1,0,1,1], k=1 輸出: true
示例 3:blog
輸入: nums = [1,2,3,1,2,3], k=2 輸出: false
1 class Solution { 2 func containsNearbyDuplicate(_ nums: [Int], _ k: Int) -> Bool { 3 //判斷 4 if nums == nil || nums.count < 2 || k < 1 5 { 6 return false 7 } 8 var map:[Int:Int] = [Int:Int]() 9 for i in 0..<(nums.count) 10 { 11 if map.keys.contains(nums[i]) 12 { 13 var sub:Int = i - map[nums[i]]! 14 if sub <= k 15 { 16 return true 17 } 18 else 19 { 20 map[nums[i]] = i 21 } 22 } 23 else 24 { 25 map[nums[i]] = i 26 } 27 } 28 return false 29 } 30 }
32ms索引
1 class Solution { 2 func containsNearbyDuplicate(_ nums: [Int], _ k: Int) -> Bool { 3 var set = Set<Int>() 4 for i in 0..<nums.count { 5 if i > k { set.remove(nums[i - k - 1]) } 6 if !set.insert(nums[i]).inserted { return true } 7 } 8 return false 9 } 10 }
32ms
1 class Solution { 2 func containsNearbyDuplicate(_ nums: [Int], _ k: Int) -> Bool { 3 var set = Set<Int>() 4 5 for i in 0..<nums.count { 6 if i > k { 7 set.remove(nums[i - k - 1]) 8 } 9 if !set.insert(nums[i]).inserted { 10 return true 11 } 12 } 13 14 return false 15 } 16 }
40ms
1 class Solution { 2 func containsNearbyDuplicate(_ nums: [Int], _ k: Int) -> Bool { 3 var map: [Int:Int] = [:] 4 5 for i in 0..<nums.count { 6 if let index = map[nums[i]], i - index <= k { 7 return true 8 } else { 9 map[nums[i]] = i 10 } 11 } 12 13 return false 14 } 15 }
44ms
1 class Solution { 2 func containsNearbyDuplicate(_ nums: [Int], _ k: Int) -> Bool { 3 var set: Set<Int> = [] 4 for i in 0..<nums.count { 5 if i > k { 6 set.remove(nums[i-k-1])//移掉無效數據 7 } 8 if !set.insert(nums[i]).inserted { 9 return true 10 } 11 } 12 return false 13 } 14 }