645. Set Mismatch
Written by Ron on 010111 April 000112011. Posted in Blog
You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.
You are given an integer array nums representing the data status of this set after the error.
Find the number that occurs twice and the number that is missing and return them in the form of an array.
Example 1:
Input: nums = [1,2,2,4]
Output: [2,3]
Example 2:
Input: nums = [1,1]
Output: [1,2]
from collections import Counter
from typing import List
class Solution:
def findErrorNums2(self, nums: List[int]) -> List[int]:
_x = sum(nums) - sum(set(nums))
_y = sum(range(1, len(nums)+1)) - sum(set(nums))
return [_x, _y]
def findErrorNums3(self, nums: List[int]) -> List[int]:
'''
[1,2,2,4]
n = 4, range_sum = 10, actual_sum = 9, set_sum = 7
duplicate = actual_sum - set_sum = 2
missing = range_sum - set_sum = 3
answer = [2,3]
'''
n = len(nums)
#range_sum = sum(range(1, n+1)) # 1 + 2 + 3 + 4 = 10
range_sum = n*(n+1)//2 # this formula also works, probably faster
actual_sum = sum(nums)
set_sum = sum(set(nums))
return [actual_sum - set_sum, range_sum - set_sum]
def findErrorNums(self, nums: List[int]) -> List[int]:
_len = len(nums)
range_sum = 0
dublicate = Counter(nums).most_common(1)[0][0]
for i in range(1, _len+1):
range_sum += i
missing = range_sum-sum(set(nums))
return [dublicate, missing]
s = Solution()
print(s.findErrorNums([4,1,2,2]))#[2,3]
print(s.findErrorNums([2,3,2]))#[2,1]
print(s.findErrorNums([3,2,2]))#[2,1]
print(s.findErrorNums([2,2]))#[2,1]
print(s.findErrorNums([1,2,2,4]))#[2,3]
print(s.findErrorNums([1,1]))#[1,2]