217. Contains Duplicate
一、题目
Problem Description:
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
二、题解
- 一道简单题,如果数组里有重复的元素就返回true,否则返回false。
2.1 Approach #1 : Sorting
先对数组进行排序;后循环判断当前元素与后一个元素是否相等来验证有无重复元素。
Time complexity :
O
(
n
l
o
g
n
)
O(nlogn)
O(nlogn). 排序方法Arrays.sort()
时间复杂度是
O
(
n
l
o
g
n
)
O(nlogn)
O(nlogn);for循环的时间复杂度是
O
(
n
)
O(n)
O(n)。时间复杂度为
m
a
x
(
O
(
l
o
g
n
)
,
O
(
n
)
)
=
O
(
n
l
o
g
n
)
max(O(logn), O(n))=O(nlogn)
max(O(logn),O(n))=O(nlogn)。
Space complexity :
O
(
1
)
O(1)
O(1).
//Sorting
//Time complexity : O(nlogn); Space complexity : O(1)
class Solution {
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;
}
}
2.2 Approach #2 : Hash Table
遍历nums数组中的所有元素。如果当前元素在HashSett中不存在,则将其加入HashSet;若存在,则直接返回true即可。
下面以HashSet集合为例,HashMap同理。
Time complexity :
O
(
n
)
O(n)
O(n). 理想情况下,HashSet的增、删、改、查等操作的时间复杂度都为
O
(
1
)
O(1)
O(1)。
Space complexity :
O
(
n
)
O(n)
O(n)
//Hash Table
//Time complexity : O(n); Space complexity : O(n)
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<>();
for(int x : nums){
if(set.contains(x)) return true;
else set.add(x);
}
return false;
}
}