#include <sys/time.h>
#include <algorithm>
#include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> us;
for( auto i : nums) {
auto it = us.find(i);
if( it == us.end() ) {
us.insert(i);
} else {
return true;
}
}
return false;
}
int main(int argc,char *argv[]) {
struct timeval tv1,tv2;
struct timezone tz;
int time1 = gettimeofday(&tv1,&tz);
vector<int> v = {1,2,3,4,5,6,7,8,9};
cout<< containsDuplicate(v) << endl;
v.push_back(3);
cout<<containsDuplicate(v)<<endl;
int time2 = gettimeofday(&tv2,&tz);
cout << "time consuming(local machine/leetcode server):"<<endl
<<"leetcode server time consuming should be less than 500ms"<<endl
<< tv2.tv_usec - tv1.tv_usec <<"us/"<<0.11*( tv2.tv_usec - tv1.tv_usec )<<"ms"<< endl;
return 0;
}
总结
- 采用unorderede_set来简化算法设计,利用其自身可以快速实现元素插入和查找的性质来实现。
- 采用C++11编写的第一道LeetCode代码,按照Google C++ style 的要求进行代码格式化。