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.
给一个整数数组,判断是否有重复值存在。
解法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 题目汇总