Come on,baby~
(1)Contains Duplicate
有自己的思路:两个for双重循环直接一个个比较,但肯定不是最优解。所以,使用Set中的HashSet(一种没有重复元素的无序集合),最优解如下:
HashSet百度链接:http://baike.baidu.com/link?url=TmKKUevqDj_4IZT_b3bFPhJJRZdY4suUZB42Ybo-9xWtoVIMLQnNT39C_OteQlMiu6jC8stsg15EfHvt11Oz9a

1 public class Solution { 2 public boolean containsDuplicate(int[] nums) { 3 if (nums != null && nums.length > 1) { 4 Set<Integer> set = new HashSet<>(nums.length); 5 for(int i : nums) { 6 if (set.contains(i)) { 7 return true; 8 } 9 else { 10 set.add(i); 11 } 12 } 13 } 14 return false; 15 } 16 }
set.contains() set.add()方法的使用
for (int i; nums)是一个foreach循环遍历,就是遍历nums这个数组中的所有值,每次把其中的一个值赋给i.
跟for (int i = 0; i < nums.length; i++) {...}效果相同。也即上述代码可改为:

1 public class Solution { 2 public boolean containsDuplicate(int[] nums) { 3 if (nums != null && nums.length > 1) { 4 Set<Integer> set = new HashSet<>(nums.length); 5 for(int i = 0; i < nums.length; i++) { 6 if (set.contains(nums[i])) { 7 return true; 8 } 9 else { 10 set.add(nums[i]); 11 } 12 } 13 } 14 return false; 15 } 16 }
【注意补充Java库中相关集合的知识--卷1P562】
第二天:忘记限制数组不为空而且数组的长度要大于1。
(2)Contains Duplicate II
题目大意:给定一个整数数组nums与一个整数k,当且仅当存在两个不同的下标i和j满足nums[i] = nums[j]并且|i-j|<=k时返回true,否则返回false。
解题思路:使用HashMap(一种存储键/值关联的数据结构),key存数组元素值,value存元素对应的索引,每来一个元素进行判断如果之前没有存过则存进去,如果之前有存则取出之前那个元素的索引值判断是否小于K,小于k返回true,不小于则存进去覆盖之前的那个【思路的重点】。

1 public class Solution { 2 public boolean containsNearbyDuplicate(int[] nums, int k) { 3 if (nums == null || nums.length < 2 || k < 1) { 4 return false; 5 } 6 Map<Integer, Integer> map = new HashMap<>(); 7 for (int i = 0; i < nums.length; i++) { 8 if (!map.containsKey(nums[i])) { 9 map.put(nums[i], i); 10 } 11 else { 12 int value = map.get(nums[i]); 13 if (i - value <= k) { 14 return true; 15 } 16 map.put(nums[i], i); 17 } 18 } 19 return false; 20 } 21 }
map.containsKey() map.get() map.put()方法的使用。【key存元素对应的索引,value存元素值为什么不对???】
!!!时间超限解法:在前一解法基础上进行修改,但是时间超限
时间超限原因???

1 public class Solution { 2 public boolean containsNearbyDuplicate(int[] nums, int k) { 3 if(nums == null || nums.length < 2) 4 return false; 5 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 6 for (int i = 0;i < nums.length; i++) { 7 if (map.containsKey(nums[i])) { 8 int j = map.get(nums[i]); 9 if (i - j <= k) { 10 return true; 11 } 12 else { 13 map.remove(nums[j]); 14 map.put(nums[i], i); 15 } 16 } 17 else { 18 map.put(nums[i], i); 19 } 20 } 21 return false; 22 } 23 }
最早的情况考虑不周解法(估计时间也超限):eg:[1,0,1,1]和1 output:false expected:true

1 public class Solution { 2 public boolean containsNearbyDuplicate(int[] nums, int k) { 3 if(nums == null || nums.length < 2) 4 return false; 5 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 6 for (int i = 0;i < nums.length; i++) { 7 if (map.containsKey(nums[i])) { 8 int j = map.get(nums[i]); 9 if (i - j <= k) { 10 return true; 11 } 12 } 13 else { 14 map.put(nums[i], i); 15 } 16 } 17 return false; 18 } 19 }