LeetCode 219. Contains Duplicate II
原题链接在这里:https://leetcode.com/problems/contains-duplicate-ii/
题目:
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.
题解:
是Contains Duplicate的进阶版题目,类似题目还有Contains Duplicate III.
建立一个HashMap hm, key是nums[i], value 是 index i.
对于nums[i], 检查它时候在 hm中,若不在,就加<nums[i], i>进去.
若是nums[i] 在 hm 中,就要看当前的i 和 hm中对应nums[i]的 value 的差值是否比k大:
若是比k 大,说明不符合条件,去掉旧的pair,添加当前pair.
若是不比k大,则return true.
这里熟练几个 HashMap functions: hm.put(key, value); hm.get(key); hm,remove(key): hm.containsKey(key).
Time Complexity: O(n). Space: O(n).
AC Java:
1 public class Solution { 2 public boolean containsNearbyDuplicate(int[] nums, int k) { 3 if(nums == null || nums.length == 0){ 4 return false; 5 } 6 HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); 7 for(int i = 0; i<nums.length; i++){ 8 if(!hm.containsKey(nums[i])){ 9 hm.put(nums[i],i); 10 }else if(i - hm.get(nums[i]) > k){ 11 hm.put(nums[i], i); 12 }else{ 13 return true; 14 } 15 } 16 return false; 17 } 18 }
AC C++:
1 class Solution { 2 public: 3 bool containsNearbyDuplicate(vector<int>& nums, int k) { 4 unordered_map<int, int> map; 5 for(int i = 0; i < nums.size(); i++){ 6 if(map.find(nums[i]) != map.end() && i - map[nums[i]] <= k){ 7 return true; 8 } 9 10 map[nums[i]] = i; 11 } 12 13 return false; 14 } 15 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一文彻底搞懂 MCP:AI 大模型的标准化工具箱
· 电商平台中订单未支付过期如何实现自动关单?
· 用 .NET NativeAOT 构建完全 distroless 的静态链接应用
· 为什么构造函数需要尽可能的简单
· 探秘 MySQL 索引底层原理,解锁数据库优化的关键密码(下)
· 一文彻底搞懂 MCP:AI 大模型的标准化工具箱
· 短信接口被刷爆:我用Nginx临时止血
· 面试官:如果某个业务量突然提升100倍QPS你会怎么做?
· .NET 平台上的开源模型训练与推理进展
· 聊聊智商税:AI知识库