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.

Example 1:

Input: [1,2,3,1]
Output: true

Example 2:

Input: [1,2,3,4]
Output: false

Example 3:

Input: [1,1,1,3,3,4,3,2,4,2]
Output: true

给一个整数数组,判断是否有重复值存在。

解法1:哈希表Hash table, 建立一个HashMap,遍历每一个数组元素。

解法2:把数组排序,然后比较每两个元素的值是否相等。

解法3:使用去重函数set(),然后比较去重后的数组长度和原数组长度。如果变小了,说明有重复元素。

Java:

class Solution {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for(int num:nums) {
if(set.contains((num))) return true;
set.add(num);
}
return false;
}
} 

Python:

class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
vis = set()
for num in nums:
if num in vis: return True
vis.add(num)
return False 

Python:

class Solution:
# @param {integer[]} nums
# @return {boolean}
def containsDuplicate(self, nums):
return len(nums) > len(set(nums))

C++:

class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_map<int, int> m;
for (int i = 0; i < nums.size(); ++i) {
if (m.find(nums[i]) != m.end()) return true;
++m[nums[i]];
}
return false;
}
};

C++:

class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
sort(nums.begin(), nums.end());
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] == nums[i - 1]) return true;
}
return false;
}
};

  

类似题目:

[LeetCode] 219. Contains Duplicate II 包含重元素 II

[LeetCode] 220. Contains Duplicate III 包含重复元素 III

 

All LeetCode Questions List 题目汇总

最新文章

  1. Android进程间的通信之Messenger
  2. Ajax最详细的参数解析和场景应用
  3. DbEntry在Vs2012里的配置
  4. Chapter7: question 49 - 50
  5. android 左右翻页
  6. 探索 OpenStack 之(15):oslo.messaging 和 Cinder 中 MessageQueue 消息的发送和接收
  7. MANIFEST.INF!JAR规范中
  8. css+js+html基础知识总结
  9. DataGrid列的合并
  10. HTTP POST和GET的区别[转]
  11. Ubuntu12.04下载Repo
  12. Bootstrap里的文件分别表示什么?都有什么用?
  13. MacOS下安装小米SQL优化工具soar
  14. FileZilla FTP Client
  15. android 常见分辨率与DPI对照表
  16. python过滤 Kubernetes api数据
  17. 序列内第k小查询(线段树)
  18. Codeforces Round #146 (Div. 1) C - Cyclical Quest 后缀自动机+最小循环节
  19. js缓存加密
  20. PhoneGap模仿微信摇一摇功能

热门文章

  1. centos6.5安装crmsh
  2. C++学习(3)——指针
  3. JVM垃圾回收算法分析与演示【纯理论】
  4. linux中的alias命令详解
  5. Object.create 以原对象为原型创建一个新对象
  6. learning java FileWriter
  7. 什么是 FOUC(无样式内容闪烁)?你如何来避免 FOUC?
  8. Coffee Break
  9. 表单提交 curl和浏览器方式
  10. Automatic Ship Detection in Optical Remote Sensing Images Based on Anomaly Detection and SPP-PCANet