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.
<Solution>
這題會用到 search 和 insert,直覺使用 hash table 來解這題
因為 hash table 的 search 和 insert 可以視作 O(1)
code 如下
C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool containsDuplicate(vector<int>& nums) { | |
unordered_set<int> hashSet; | |
for(const int n : nums) { | |
if(hashSet.count(n)) { | |
return true; | |
} | |
hashSet.insert(n); | |
} | |
return false; | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public boolean containsDuplicate(int[] nums) { | |
HashSet<Integer> hashSet = new HashSet<>(); | |
for(final int n : nums) { | |
if(hashSet.contains(n)) { | |
return true; | |
} | |
hashSet.add(n); | |
} | |
return false; | |
} | |
} |
沒有留言:
張貼留言