Contains Duplicate II
2015-05-31 21:33
429 查看
Contains Duplicate II
问题:
Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between iand j is at most k.
思路:
hash表
我的代码:
View Code
学习之处:
在数组里面的坐标问题可以考虑用hashtable进行存储,用空间换时间是一个常用的策略。
问题:
Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between iand j is at most k.
思路:
hash表
我的代码:
public class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { if(nums==null || nums.length==0 || k<0 ) return false; HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>(); for(int i=0; i<nums.length; i++) { if(hash.containsKey(nums[i])) { if(i-hash.get(nums[i]) <= k) return true; hash.put(nums[i], i); } else hash.put(nums[i], i); } return false; } }
View Code
学习之处:
在数组里面的坐标问题可以考虑用hashtable进行存储,用空间换时间是一个常用的策略。
相关文章推荐
- 浅析_tmain()与main()的区别
- 017_04Canvas和Paint的用法
- [leetcode] Contains Duplicate
- Rails: No such file or directory - getcwd
- Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default
- LeetCode 219:Contains Duplicate II
- LeetCode 217:Contains Duplicate
- SGU121 Bridges painting
- Internal Sorting: Straight insertion: Sorting by Insertion
- Internal Sorting: Cocktail-shaker sort: Sorting by Exchanging
- Windows 动态磁盘卷:简单卷、跨区卷 、带区卷 、镜像卷 、RAID5卷 相关配置操作
- Hadoop: Hadoop oozie main sub workflow.xml configuration
- signal raise alarm用法
- Internal Sorting: Straight selection sort: Sorting by Selection
- solr DataImportHandler (数据相关操作)
- [leetcode] Contains Duplicate II
- [leedcode219]Contains Duplicate II
- SGU119 Magic Pairs
- Internal Sorting: Straight Two-way Merge Sort: Sorting by Merging
- 535 Error:authentication failed