Leetcode 217. Contains Duplicate
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:
nums = [1,2,3,1]
true
nums = [1,2,3,4]
false
nums = [1,1,1,3,3,4,3,2,4,2]
true
Before we start solving the problem, here are a few clarifying questions and assumptions:
We can solve this problem using one of the following approaches:
true
.false
.true
.false
.Approach: We will use the hash set approach as it is more efficient in terms of time complexity.
Here is the C++ code that uses a hash set to determine if the array contains any duplicates.
#include <vector>
#include <unordered_set>
class Solution {
public:
bool containsDuplicate(std::vector<int>& nums) {
std::unordered_set<int> seen;
for(const int& num : nums) {
// Check if the number is already in the set
if(seen.find(num) != seen.end()) {
return true;
}
// Insert the number into the set
seen.insert(num);
}
// If we found no duplicates, return false
return false;
}
};
// Example usage
// int main() {
// Solution solution;
// std::vector<int> nums = {1, 2, 3, 1};
// bool result = solution.containsDuplicate(nums);
// std::cout << (result ? "true" : "false") << std::endl; // Output: true
// return 0;
// }
This solution effectively balances time efficiency and space complexity well for typical constraints seen in coding interviews.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?