【leetcode】217. Contains Duplicate

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

总结

  1. 采用unorderede_set来简化算法设计,利用其自身可以快速实现元素插入和查找的性质来实现。
  2. 采用C++11编写的第一道LeetCode代码,按照Google C++ style 的要求进行代码格式化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值