题目:
存在重复元素
题目要求是查找是否存在重复出现的元素。第一想法是通过两重循环查找对比。优化点:内层循环只需要查找外层循环角标后面的元素。
class Solution {
public boolean containsDuplicate(int[] nums) {
for(int i =0; i< nums.length; i++) {
for(int j = i + 1; j < nums.length; j++) {
if(nums[i] == nums[j]) {
return true;
}
}
}
return false;
}
}
超出时间限制,看来是不能用这种方法了。
第二种,利用HashMap。key为元素,value为元素个数。优化点:不需遍历完整个数组,判断插入元素前,获取该key是否存在对应的值,若hash表中已存在值,则可判断重复。
class Solution {
public boolean containsDuplicate(int[] nums) {
Map<Integer,Integer> map = new HashMap((int)(nums.length / 0.75f + 1));
for(int i =0; i< nums.length; i++) {
Integer num = map.get(nums[i]);
if(num != null) {
return true;
}
map.put(nums[i], 1);
}
return false;
}
}
执行效率看来并不理想。
第三种,联想到另一题 只出现一次的数字,通过异或操作完成,执行效率颇高。因此想有没有相应的位运算。