zoukankan      html  css  js  c++  java
  • LeetCode【第217题】Contains Duplicate

    题目:

    '''
    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
    '''
    
    '''
    给定一个整数数组,找到该数组是否包含任何重复。 如果任何值在数组中至少出现两次,则函数应返回true,如果每个元素都不同,则函数应返回false。
    '''

    解法一55ms:

    class Solution(object):
        def containsDuplicate(self, nums):
            """
            :type nums: List[int]
            :rtype: bool
            """
            if len(nums) == 0:
                return False
            else:
                arr = {}
                for i in range(len(nums)):
                    if nums[i] in arr:
                        return True
                    else:
                        arr[nums[i]] = i
                else:
                    return False

    解法二48ms:(一行)

    class Solution(object):
        def containsDuplicate(self, nums):
            """
            :type nums: List[int]
            :rtype: bool
            """
            return len(nums) != len(set(nums))
  • 相关阅读:
    创建对象的七种方式
    设计模式之工厂模式
    设计模式之单例模式
    排序算法之插入排序
    排序算法之选择排序
    类及对象初体验
    排序算法之冒泡排序
    迭代器和生成器
    装饰器
    函数进阶
  • 原文地址:https://www.cnblogs.com/zingp/p/6213186.html
Copyright © 2011-2022 走看看