2017年11月19日 星期日

[LeetCode] 217. Contains Duplicate

轉自LeetCode

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++

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;
}
};
Java

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;
}
}

沒有留言:

張貼留言