LeetCode 217:存在重复元素 Contains Duplicate

简介: 题目:给定一个整数数组,判断是否存在重复元素。Given an array of integers, find if the array contains any duplicates.如果任何值在数组中出现至少两次,函数返回 true。

题目:

给定一个整数数组,判断是否存在重复元素。

Given an array of integers, find if the array contains any duplicates.

如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。

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:

输入: [1,2,3,1]
输出: true

示例 2:

输入: [1,2,3,4]
输出: false

示例 3:

输入: [1,1,1,3,3,4,3,2,4,2]
输出: true

解题思路:

​ 排序数组,连续两个数相等则证明存在重复元素。

​ 直接用哈希集合:新建一个哈希集合,逐个向集合内添加元素,如果遇到元素未添加成功,则证明存在重复元素,返回 True ,反之返回 False。

代码:

这里用的哈希集合解题

Java:

class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new LinkedHashSet<>();
        for (int num : nums) {
            if (!set.add(num)) return true; //加入集合未成功,证明集合内已有一个相同元素,返回False
        }
        return false;
    }
}

Python:

​ Python中 set() 函数可以直接将数组转化为哈希集合。直接比较转化后的哈希集合长度与原数组长度是否相等,相等证明原数组无重复元素,不相等则证明原数组含有重复元素。

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        return len(nums) != len(set(nums)) #比较长度

欢迎关注微.信公.众号:爱写Bug

目录
相关文章
|
1月前
|
算法 Java
[Java·算法·简单] LeetCode 27. 移除元素 详细解读
[Java·算法·简单] LeetCode 27. 移除元素 详细解读
23 1
|
1月前
|
算法 C语言
【C语言】Leetcode 27.移除元素
【C语言】Leetcode 27.移除元素
21 0
【C语言】Leetcode 27.移除元素
|
1月前
|
C++
两种解法解决 LeetCode 27. 移除元素【C++】
两种解法解决 LeetCode 27. 移除元素【C++】
【移除链表元素】LeetCode第203题讲解
【移除链表元素】LeetCode第203题讲解
|
1月前
|
算法
LeetCode[题解] 1261. 在受污染的二叉树中查找元素
LeetCode[题解] 1261. 在受污染的二叉树中查找元素
16 1
|
3月前
leetcode:203. 移除链表元素(有哨兵位的单链表和无哨兵位的单链表)
leetcode:203. 移除链表元素(有哨兵位的单链表和无哨兵位的单链表)
19 0
|
2天前
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
|
7天前
|
算法
代码随想录算法训练营第五十七天 | LeetCode 739. 每日温度、496. 下一个更大元素 I
代码随想录算法训练营第五十七天 | LeetCode 739. 每日温度、496. 下一个更大元素 I
12 3
|
11天前
|
算法
【力扣】169. 多数元素
【力扣】169. 多数元素
|
1月前
|
存储 JavaScript
leetcode82. 删除排序链表中的重复元素 II
leetcode82. 删除排序链表中的重复元素 II
22 0