在Leetcode上看到一道题,跟之前做的关于找“Single Number" 有点类似。这次的题目是这样的:
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: Falst
现在就直接上Java代码:
class Solution {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> set = new HashSet<Integer>();
for(int i : nums) {
if(set.contains(i)){
return true;
} else {
set.add(i);
}
}
return false;
}
}
之前也想到一个方法,是先把数组进行排序,然后将排序好的数组进行相连两个进行比较,如果是相等的,就返回true, 否则返回false. 但是这种方法,用c来实现,跑出的结果是Runtime error, 这就不符合题目的要求的时间复杂度了。
如果有哪里写的不对,请指出来!