美文网首页
leetcode 217 python 存在重复元素

leetcode 217 python 存在重复元素

作者: 慧鑫coming | 来源:发表于2019-01-31 14:28 被阅读0次

传送门

题目要求

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

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

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

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

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

思路一

利用set()去除列表中重复元素,若set前后长度相等,说明没有重复元素

→_→ talk is cheap, show me the code

class Solution:
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        return len(nums) != len(set(nums))

思路二

遍历列表,已元素为键,出现次数为值,如果出现次数有大于1次的,说明存在重复元素

→_→ talk is cheap, show me the code

class Solution:
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        d = dict()
        for i in nums:
            n = d.get(i, 0)
            n += 1
            d[i] = n
            if n > 1:
                return True
        return False
        

相关文章

网友评论

      本文标题:leetcode 217 python 存在重复元素

      本文链接:https://www.haomeiwen.com/subject/gtwksqtx.html