leetcode题解之Find the Duplicate Number

1、题目描述

2、分析

利用C++的 标准模板库 set 对数组进行读取,然后插入,如果检测到元素已经在set内部,则返回该元素值即可。时间复杂度为 O(n),空间复杂度为 O(n);

3、代码

 1 int findDuplicate(vector<int>& nums) {
 2         std::set<int> myset;
 3         std::pair< std::set<int>::iterator,bool > ret;
 4         
 5         for( int i = 0 ; i< nums.size(); i++)
 6         {
 7             ret = myset.insert( nums[i] );
 8             if( ret.second == false )
 9             {
10                 return nums[i];
11             }
12         }
13     }

猜你喜欢

转载自www.cnblogs.com/wangxiaoyong/p/9029549.html
今日推荐