Leetcode217. Contains Duplicate
2016-03-03 16:55
465 查看
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.
Subscribe to see which companies asked this question
题目:给定一个整数数组,判断数组中是否有重复数字
思路1:
使用hash表,先构建,然后遍历,发现value大于1则判断有重复
思路2:
使用异或位运算,如果没有重复,则结果不为0,反之,当异或结果第一次变为0时,即可推出程序,判断数组中有重复数字!
思路3:对数组排序,遍历相邻数字是否相等
Subscribe to see which companies asked this question
题目:给定一个整数数组,判断数组中是否有重复数字
思路1:
使用hash表,先构建,然后遍历,发现value大于1则判断有重复
class Solution { public: bool containsDuplicate(vector<int>& nums) { int tmp=0; unordered_map<int,int> hash; for(auto a:nums) hash[a]++; for(auto a:hash) if(a.second>=2) { tmp=1; break; } if(tmp==1) return true; else return false; } };
思路2:
使用异或位运算,如果没有重复,则结果不为0,反之,当异或结果第一次变为0时,即可推出程序,判断数组中有重复数字!
思路3:对数组排序,遍历相邻数字是否相等
class Solution { public: bool containsDuplicate(vector<int>& nums) { std::sort(nums.begin(), nums.end()); for (int i = 1; i < nums.size(); i++) { if (nums[i-1] == nums[i]) return true; } return false; } };
相关文章推荐
- AP核MAILBOX地址的初始化和启动过程(基于ARM64 的 APCI Parking protocol)
- 线程 WebContainer 已保持活动状态 N 毫秒,此线程可能已挂起
- retain和copy还有assign的区别,atomic和nonatomic的用途
- # _http_outgoing JS的错误: The header content contains invalid characters
- AIR客户端-高效处理图片缩略图的解决思路1
- VR开发中性能问题—OculusWaitForGPU
- VR开发中性能问题—OculusWaitForGPU
- 1090. Highest Price in Supply Chain (25)
- codeforces 627B B. Factory Repairs(线段树)
- data Mining with Weka: Trailer More Data Mining with Weka 用weka 进行数据挖掘 Weka 用weka 进行更多数据挖掘
- 永远不要在循环之外调用wait方法
- 永远不要在循环之外调用wait方法
- DLL中dllmain重定义的解决办法
- Fatal: the Postfix mail system is already running 的解决方案
- List对于自定义类型,使用contains
- Email 下载音频附件完成后播放不显示名称
- wait_event_interruptible 使用方法
- 如何: 如何提供自己 DllMain MFC 的规则 DLL 中
- 【转】traits技术及模板偏特化
- 运行目录和工作目录 http://blog.csdn.net/ghevinn/article/details/17399001