今天刷 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;
}
}