在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 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. Example 1: Input: nums = 3
Output: true
Example 2: Input: nums = 1
Output: true
Example 3: Input: nums = 2 Output: false 给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。 示例 1: 输入: nums = [1,2,3,1], k= 3 输出: true 示例 2: 输入: nums = [1,0,1,1], k=1 输出: true 示例 3: 输入: 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 }
|
请发表评论