Leetcode刷题 Day6 217. Contains Duplicate

来源:互联网 发布:网络购物平台有哪些 编辑:程序博客网 时间:2024/06/12 23:11

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.

解法一:

看到一个非常漂亮的答案:

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

利用python数据结构set去重的特性,漂亮!

42ms,打败了97.47%的运行时间。

解法二:

我想这道题本身考的不是python解法一NB的功能

所以我自己写了个通用的算法:

先将list按增序排序

遍历从第1个数字到最后一个数字,比较当前数字与其前一个是否相等。如果相等则证明有重复

如果遍历结束都没有重复则证明该list没有重复


class Solution(object):    def containsDuplicate(self, nums):        """        :type nums: List[int]        :rtype: bool        """        nums=sorted(nums)                for i in range(1,len(nums)):             if nums[i] == nums[i-1]:                    return True        return False                
#52ms,打败了54%的用户


Contains Duplicate II


Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.


这题不容易读明白,它意思是:找一个数组中是否有重复的数字,且这两个数字的index间距不能超过k

比Contains Duplicate I的难点在于:

不能先对数组排序了,否则会改变index就不符合题意了。


解法如下:

class Solution(object):    def containsNearbyDuplicate(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: bool        """        dic = {}        for i, v in enumerate(nums):            if v in dic and i - dic[v] <= k:                return True            dic[v] = i        return False

这个方法除去k的限制,就是说用dict这种思想同样适合于Contains Duplicate I

52ms,打败了60%

这也是我第一次接触enumerate()这个函数,解法二中 i代表index,v代表value, for i , v in enumerate(nums)是把nums里的index和value遍历出来。当同时需要index和value时用enumerate()函数写比较方便


以上两道都是初级题目,下面是中级题目:



https://leetcode.com/problems/contains-duplicate-iii/discuss/ 

后续还要做


原创粉丝点击