LeetCode OJ:Contains DuplicateII(是否包含重复II)
2015-10-17 14:41
537 查看
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 difference between i and jis at most k.
这题上上一篇博客的延伸,问的是k长的距离内有没有两个数是相等的,类似一个滑动窗口问题,方法比较简单,使用一个map记下上次数出现的位置就可以了,代码如下:
java版本的代码如下所示,用的方法都是一样的:
这题上上一篇博客的延伸,问的是k长的距离内有没有两个数是相等的,类似一个滑动窗口问题,方法比较简单,使用一个map记下上次数出现的位置就可以了,代码如下:
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { map<int, int> ret; int sz = nums.size(); for (int i = 0; i < sz; ++i){ if (ret.find(nums[i]) != ret.end() && i - ret[nums[i]] <= k) return true; else ret[nums[i]] = i; } return false; } };
java版本的代码如下所示,用的方法都是一样的:
public class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { HashMap<Integer, Integer> m = new HashMap<Integer, Integer>(); for(int i = 0; i < nums.length; ++i){ if(m.containsKey(nums[i])) if(i-m.get(nums[i]) <= k) return true; m.put(nums[i], i);//放在这里有两个原因,如果本来存在将index更新到最近的位置,如果不存在就将它放到map中起 } return false; } }
相关文章推荐
- LeetCode OJ:Contains Duplicate(是否包含重复)
- Code Forces 585 B. Phillip and Trains(BFS)
- 构造函数中抛出的异常 http://blog.csdn.net/deyili/article/details/6332760
- No Entertainment!
- apk安装故障INSTALL_FAILED_INSUFFICIENT_STORAGE
- hdoj 2389 Rain on your Parade 【HK】
- vim 集成环境搭建之vim-main
- Mybatis错误:Parameter 'XXX' not found. Available parameters are [1, 0, param1, param2]
- Mybatis错误:Parameter 'XXX' not found. Available parameters are [1, 0, param1, param2]
- C++中的RAII机制 http://www.jellythink.com/archives/101
- AIDL(1)
- RAII惯用法:C++资源管理的利器 http://www.cnblogs.com/hsinwang/articles/214663.html
- CF Round #325 Div2 D. Phillip and Trains
- LeetCode -- Climbing Stairs
- 配置RAID
- golang辟谣之RAII
- Naive Bayesian
- wait_event_interruptible 在驱动中的应用
- TIME_WAIT是什么?
- 系统关键字 retain assign copy