存在重复元素
第一次尝试
思路
双从循环,整个遍历一遍,一个一个的比对,如果有相同的直接返回true
代码
class Solution {
public boolean containsDuplicate(int[] nums) {
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
if (i != j && nums[i] == nums[j]) {
return true;
}
}
}
return false;
}
}
提交结果
小结
直接超时,此法不通,需要减少一重循环
第二次尝试
思路
先把数组排序了,排序完成后,如果相邻元素是相等的,返回true
代码
class Solution3{
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == nums[i+1]) {
return true;
}
}
return false;
}
}
提交结果
第三次尝试
思路
使用Java流,去重后查看长度和原数组长度是否相等
代码
class Solution {
public boolean containsDuplicate(int[] nums) {
return Arrays.stream(nums).distinct().count() != nums.length;
}
}
提交结果
小结
此方法更慢
第四次尝试
思路
使用Hash表键不重复
代码
class Solution {
public boolean containsDuplicate(int[] nums) {
Map<Integer,Integer> map = new HashMap<>();
for (int num : nums) {
if (map.getOrDefault(num, 0) == 0) {
map.put(num, 1);
} else {
return true;
}
}
return false;
}
}
小结
慢的无法形容
总结
综上,还是排序的目前最快
burybell@163.com