Algorithms—219.Contains Duplicate II
2015-06-03 21:50
316 查看
思路,首先将数组nums中前k个数放入map中查看是否有相同的,如果在,返回true;如果没有,添加;
然后,检查后面的每一个数是否在map中,如果在,返回ture;如果没有,添加,并删除map中最先添加的那个;public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if(nums.length<=1){
return false;
}
Map<Integer, String> map = new HashMap<Integer, String>();
for (int i = 0; i < nums.length; i++) {
if (map.get(nums[i]) == null) {
map.put(nums[i], "");
if (i >= k) {
map.remove(nums[i - k]);
}
} else {
return true;
}
}
return false;
}
}
然后,检查后面的每一个数是否在map中,如果在,返回ture;如果没有,添加,并删除map中最先添加的那个;public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if(nums.length<=1){
return false;
}
Map<Integer, String> map = new HashMap<Integer, String>();
for (int i = 0; i < nums.length; i++) {
if (map.get(nums[i]) == null) {
map.put(nums[i], "");
if (i >= k) {
map.remove(nums[i - k]);
}
} else {
return true;
}
}
return false;
}
}
相关文章推荐
- (转载)ADS启动问题:The unexpected failure of a COM operation suggests that MWComHelpers may be missing
- Contains Duplicate III
- poj 3250 Bad Hair Day 单调栈
- Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost.
- hdu - 1104 Remainder (bfs + 数论)
- Error: Failed to launch instance "win7": Please try again later [Error: No valid host was found. ].
- An animation block that calls the subviews updateConstraints method
- 帝国留言板管理员回复发送EMAIL通知客户
- 219. Contains Duplicate II
- ARC中Retain Cycle揭秘
- 217. Contains Duplicate
- AEAI DP_V3.4.0_20150601升级说明
- postfix+extmail+dovecot+ courier-authlib 实现公网邮件服务器
- 解决sublimeText3无法安装插件问题 -- There are no packages available for installation
- Leetcode Problem.217 —Contains Duplicate
- 使用NSSearchPathForDirectoriesInDomains等获取路径的方法时的注意事项
- tools:context=".MainActivity的作用
- AIX下新建账户
- 控制台应用程序的Main方法
- * failed to start daemon *