2026-06-01 16:12:21 +08:00
|
|
|
#+PROPERTY: STUDY_DECK_02
|
2026-06-01 17:35:55 +08:00
|
|
|
* DONE 0217. Contains Duplicate :easy:
|
2026-06-01 02:33:30 +08:00
|
|
|
:PROPERTIES:
|
2026-06-01 17:22:07 +08:00
|
|
|
:NEETCODE: [[file:../../roadmap.org::*0217. Contains Duplicate][0217. Contains Duplicate]]
|
2026-06-01 02:33:30 +08:00
|
|
|
:END:
|
|
|
|
|
|
2026-06-01 17:22:07 +08:00
|
|
|
Given an integer array ~nums~, return ~true~ if any value appears *at least twice* in the array, and return ~false~ if every element is distinct.
|
|
|
|
|
|
|
|
|
|
*Example 1:*
|
|
|
|
|
|
|
|
|
|
*Input:* nums = [1,2,3,1]
|
|
|
|
|
|
|
|
|
|
*Output:* true
|
|
|
|
|
|
|
|
|
|
*Explanation:*
|
|
|
|
|
|
|
|
|
|
The element 1 occurs at the indices 0 and 3.
|
|
|
|
|
|
|
|
|
|
*Example 2:*
|
|
|
|
|
|
|
|
|
|
*Input:* nums = [1,2,3,4]
|
|
|
|
|
|
|
|
|
|
*Output:* false
|
|
|
|
|
|
|
|
|
|
*Explanation:*
|
|
|
|
|
|
|
|
|
|
All elements are distinct.
|
|
|
|
|
|
|
|
|
|
*Example 3:*
|
|
|
|
|
|
|
|
|
|
*Input:* nums = [1,1,1,3,3,4,3,2,4,2]
|
|
|
|
|
|
|
|
|
|
*Output:* true
|
|
|
|
|
|
|
|
|
|
*Constraints:*
|
|
|
|
|
|
|
|
|
|
- ~1 <= nums.length <= 10^{5}~
|
|
|
|
|
|
|
|
|
|
- ~-10^{9} <= nums[i] <= 10^{9}~
|
|
|
|
|
|
2026-06-01 17:35:55 +08:00
|
|
|
** DONE Approach
|
2026-06-01 02:39:53 +08:00
|
|
|
Write your approach here.
|
|
|
|
|
|
2026-06-01 17:35:55 +08:00
|
|
|
** DONE Python
|
2026-06-01 02:39:53 +08:00
|
|
|
#+begin_src python
|
2026-06-01 17:22:07 +08:00
|
|
|
class Solution:
|
|
|
|
|
def containsDuplicate(self, nums: List[int]) -> bool:
|
2026-06-01 17:23:01 +08:00
|
|
|
s = set()
|
|
|
|
|
for x in nums:
|
|
|
|
|
if x in s:
|
|
|
|
|
return True
|
|
|
|
|
s.add(x)
|
|
|
|
|
return False
|
2026-06-01 02:39:53 +08:00
|
|
|
#+end_src
|
|
|
|
|
|
2026-06-01 17:35:55 +08:00
|
|
|
** DONE C++
|
2026-06-01 02:33:30 +08:00
|
|
|
#+begin_src cpp
|
2026-06-01 17:35:55 +08:00
|
|
|
#include <vector>
|
|
|
|
|
#include <set>
|
2026-06-01 17:22:07 +08:00
|
|
|
class Solution {
|
|
|
|
|
public:
|
2026-06-01 17:35:55 +08:00
|
|
|
bool containsDuplicate(std::vector<int>& nums) {
|
|
|
|
|
std::set<int> s;
|
|
|
|
|
for (int x: nums) {
|
|
|
|
|
if (s.contains(x)) {
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
s.insert(x);
|
2026-06-01 17:22:07 +08:00
|
|
|
}
|
2026-06-01 17:35:55 +08:00
|
|
|
return false;
|
|
|
|
|
}
|
2026-06-01 17:22:07 +08:00
|
|
|
};
|
2026-06-01 02:33:30 +08:00
|
|
|
#+end_src
|