Leetcode 645 FindErrorNum

The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.

Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.

Example 1:

Input: nums = [1,2,2,4]
Output: [2,3]

Note:

  1. The given array size will in the range [2, 10000].
  2. The given array's numbers won't have any order.

我原创的第一种方法,对是对,但是超时了,没有AC:
class Solution(object):
    def findErrorNums(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """

        key_count_dict = {}
        errornum = None  # 重复的数字
        missnum = None  # 缺失的数字
        for num in nums:
            if (num in key_count_dict.keys()):  # 如果key存在
                key_count_dict[num] = key_count_dict[num] + 1
                errornum = num  # 记录是哪个数字重复了两遍
            else:  # 如果key不存在
                key_count_dict[num] = 1



        for i in range(1, max(key_count_dict.keys()) + 1):  # 包含max本身
                if i not in key_count_dict.keys():
                    missnum = i
                    break

        if (missnum==None):
                 missnum=max(key_count_dict.keys()) + 1

        return [errornum, missnum]



sol=Solution()
nums=[1, 3, 3, 4]
result=sol.findErrorNums(nums)
print (result)





可以看出这种方法确实很笨,时间复杂度O(n的平方)

于是我就思考怎么优化,有了方法二:

class Solution(object):
    def findErrorNums(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """

        count = [0] * (len(nums) + 1)#初始化,记得+1,因为可能缺失的值是max+1
        for x in nums:
            count[x] += 1
        for x in range(1, len(nums) + 1):
            if count[x] == 2:
                twice = x
            if count[x] == 0:
                never = x
        return [twice,never]

参考了discussion,因为这道题的标签是 hashtable,所以我印象中错误的认为python中只有dict才能实现hashtable。
通过这道题我明白了 hashtable是一种思想,用list 也能实现

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值