[Swift]LeetCode219. 存在重复元素 II | Contains Duplicate II
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9745631.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.
Example 1:
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。
示例 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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了