LeetCode(43)-Contains Duplicate II
2016-04-11 11:27
211 查看
题目:
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 j is at most k.
思路:
给定一个数组a,和一个整数k,题意是判断一个数组里面,有没有重复的两个元素,坐标是i和j,且i和j只差大于等于k。考虑用hashMap
代码:
public class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { if(nums==null || nums.length<2) return false; //key=int, val=index Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i=0; i<nums.length; i++) { if(map.containsKey(nums[i])) { int j = map.get(nums[i]); if(i-j<=k) {return true; }else{ map.remove(j); map.put(nums[i], i); } } else { map.put(nums[i], i); } } return false; } }
相关文章推荐
- 报错:failed to get the task for process XXX(解决方案)
- Domain generalization 简介
- BaiduMap---百度地图官方Demo之调用百度地图(介绍如何调启百度地图实现自身业务功能)
- Command /usr/bin/codesign failed with exit code 1
- jenkins排错---Waiting for next available executor
- 使用anddroid studio编译报错: Error:Execution failed for task ':mergeDebugResources'.
- 关于人工智能和人类未来的吐槽
- git:Please enter a commit message to explain why this merge is necessary
- 分类模型的性能评估——以SAS Logistic回归为例(3): Lift和Gain
- 解决Failed to parse SourceMap: http:xxx 问题
- 6.8.1 qmgr_active_drain函数:从active队列发信
- 我与小娜(50):聂卫平向人工智能致敬
- LeetCode 219. Contains Duplicate II
- hdu 1021 Fibonacci Again
- Z-Stack分析--main函数
- PERC5/6 RAID如何配置?整合
- aidl笔记
- sleep()和wait()的区别
- USACO 修理牛棚 Barn Repair
- DELL服务器RAID H700,PERC H800阵列卡配置中文完全手册图解