217. 存在重复元素

题目链接:https://leetcode-cn.com/problems/contains-duplicate/

执行用时:140 ms, 在所有 Swift 提交中击败了74.12%的用户
内存消耗:15.4 MB, 在所有 Swift 提交中击败了67.09%的用户

将数组排序后两两比较

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
func containsDuplicate(_ nums: [Int]) -> Bool {
let n = nums.count
var arr = nums.sorted()
for i in 0 ..< n-1 {
if arr[i] == arr[i+1] {
return true
}
}
return false
}
}

将数组转为set后比较长度是否一致

1
2
3
4
5
6
class Solution {
func containsDuplicate(_ nums: [Int]) -> Bool {
let set = Set<Int>(nums)
return set.count < nums.count
}
}

java, 加入set失败时则表明重复

执行用时:4 ms, 在所有 Java 提交中击败了77.44%的用户
内存消耗:51.4 MB, 在所有 Java 提交中击败了8.63%的用户

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int i:
nums) {
if (!set.add(i)) {
return true;
}
}
return false;
}
}

217. 存在重复元素
https://pisces34.github.io/2021/09/19/leetcode/217/
发布于
2021年9月19日
许可协议