Given an integer array, return true if any value appears at least twice, and false if every element is distinct.
An empty array and a single-element array are both distinct, so both return false.
containsDuplicate({1, 2, 3, 1})
The wrong ones are this same code with between two and five lines changed. Some of those changes do not compile. There is no Run button: running all three would turn this into a vote rather than a reading.
| 1 | bool containsDuplicate(const vector<int>& nums) { |
| 2 | |
| 3 | unordered_set<int> seen; |
| 4 | |
| 5 | for (int x : nums) { |
| 6 | if (!(seen.count(x))) { |
| 7 | return true; |
| 8 | } |
| 9 | } |
| 10 | |
| 11 | return false; |
| 12 | } |
| 1 | bool containsDuplicate(const vector<int>& nums) { |
| 2 | |
| 3 | unordered_set<int> seen; |
| 4 | |
| 5 | for (int x : nums) { |
| 6 | if (seen.count(x)) { |
| 7 | return true; |
| 8 | } |
| 9 | seen.insert(x); |
| 10 | } |
| 11 | |
| 12 | return false; |
| 13 | } |
| 1 | bool containsDuplicate(const vector<int>& nums) { |
| 2 | |
| 3 | unordered_set<int> seen; |
| 4 | |
| 5 | for (int x : nums) { |
| 6 | if (!(seen.count(x))) { |
| 7 | return true; |
| 8 | } |
| 9 | } |
| 10 | |
| 11 | return true; |
| 12 | } |