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:
- The given array size will in the range [2, 10000].
- 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 也能实现