遍历数组找出有没有重复的元素 首先想到用一个数组记录出现的元素的个数

代码:

public class Solution {
public boolean containsDuplicate(int[] nums) {
if(nums.length == 0) return true;
int[] checkElement = new int[Integer.MAX_VALUE];
for(int i = 0; i < nums.length; i++){
if(checkElement[nums[i]] > 0) return false;
checkElement[nums[i]]++;
}
return true;
}
}

 

space cost太大: requested array size exceed VM limit

用hashmap来做吧:

public class Solution {
public boolean containsDuplicate(int[] nums) {
if(nums.length == 0) return false;
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
if(map.containsKey(nums[i])) return true;
map.put(nums[i],1);
}
return false;
}
}

 

Accepted,但是runtime 不是很好。考虑下别的办法。

先把array排序一下 查了一下Arrays.sort() 用的是mergesort() runtime is O(nlog(n))

代码:

public class Solution {
public boolean containsDuplicate(int[] nums) {
if(nums.length == 0) return false;
Arrays.sort(nums);
//boolean[] checkElement = new boolean[15000];
//Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length-1; i++){
if(nums[i] == nums[i+1]) return true;
}
return false;
}
}

posted on 2016-01-12 05:42  爱推理的骑士  阅读(114)  评论(0编辑  收藏  举报