今天刷 leetcode "4. Median of Two Sorted Arrays",半天没看懂log(m +n) 算法的具体细节,十分懊恼,做一道简单题放松一下。这道题去北邮面试的时候还考过,当初直接用一个数组s,用index存input数组的值,用s[index] ,存储对应的下标,如果发现s[index]不是0,则说明已经出现,故重复。(默认index从1开始)
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
solution:
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<>();
int len = nums.length;
for(int num:nums){
//add方法 插入成功返回true,有冗余数据失败返回false
if(!set.add(num)){
return true;
}
}
return false;
}
}
本文介绍了一种使用HashSet解决LeetCode题目中数组重复元素检测的方法。通过实例展示,如输入[1,2,3,1],输出为true;输入[1,2,3,4],输出为false。解决方案利用了HashSet的add方法,当尝试添加已存在的元素时,会返回false,从而判断数组中是否存在重复元素。
669

被折叠的 条评论
为什么被折叠?



