Skip to content

Commit 2ec908a

Browse files
committed
add 217
1 parent c5cc7b7 commit 2ec908a

File tree

3 files changed

+61
-1
lines changed

3 files changed

+61
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
| 121 | [Best Time to Buy and Sell Stock][121] |
2020
| 122 | [Best Time to Buy and Sell Stock II][122] |
2121
| 189 | [Rotate Array][189] |
22-
22+
| 217 | [Contains Duplicate][217] |
2323

2424

2525
[leetcode]: https://leetcode.com/problemset/all/
@@ -30,3 +30,4 @@
3030
[121]: https://github.com/andavid/leetcode-java/blob/master/note/121/README.md
3131
[122]: https://github.com/andavid/leetcode-java/blob/master/note/122/README.md
3232
[189]: https://github.com/andavid/leetcode-java/blob/master/note/189/README.md
33+
[217]: https://github.com/andavid/leetcode-java/blob/master/note/217/README.md

note/217/README.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# [Contains Duplicate][title]
2+
3+
## Description
4+
5+
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.
6+
7+
## 思路
8+
9+
给定一个数组,判断数组里是否包含重复元素。
10+
11+
1. 使用两层 for 循环遍历数组元素是否相等,会报 `Time Limit Exceeded`,时间复杂度 O(n<sup>2</sup>),空间复杂度 O(1)。
12+
1. 对数组先排序,然后扫描一遍数组看相邻元素是否相等。时间复杂度取决于排序算法。
13+
1. 使用 HashSet(集合里不允许有重复的值),把数组元素全部添加到集合里,如何集合长度和数组长度不一致,说明有重复元素。时间复杂度 O(n),空间复杂度 O(n)。此方法相对较优。
14+
15+
## [完整代码][src]
16+
17+
```java
18+
class Solution {
19+
public boolean containsDuplicate(int[] nums) {
20+
if (null == nums || 0 == nums.length) {
21+
return false;
22+
}
23+
24+
Set<Integer> set = new HashSet<Integer>();
25+
for (int num : nums) {
26+
set.add(num);
27+
}
28+
29+
return (set.size() != nums.length) ? true : false;
30+
}
31+
}
32+
```
33+
34+
[title]: https://leetcode.com/problems/contains-duplicate
35+
[src]: https://github.com/andavid/leetcode-java/blob/master/src/com/andavid/leetcode/_217/Solution.java
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import java.util.*;
2+
3+
class Solution {
4+
public boolean containsDuplicate(int[] nums) {
5+
if (null == nums || 0 == nums.length) {
6+
return false;
7+
}
8+
9+
Set<Integer> set = new HashSet<Integer>();
10+
for (int num : nums) {
11+
set.add(num);
12+
}
13+
14+
return (set.size() != nums.length) ? true : false;
15+
}
16+
17+
public static void main(String[] args) {
18+
Solution solution = new Solution();
19+
System.out.println(solution.containsDuplicate(new int[]
20+
{1, 2, 1, 3, 4}));
21+
System.out.println(solution.containsDuplicate(new int[]
22+
{1, 2, 3, 4, 5}));
23+
}
24+
}

0 commit comments

Comments
 (0)