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 this set got duplicated which caused another number to be missing. You need to return an array of two numbers, one of which is the duplicated number and the other is the missing number.
n
? Are we dealing with very large numbers?Without loss of generality, we’ll assume the following for the problem:
nums
containing n
integers.[duplicated, missing]
.n
natural numbers and the actual sum of the given array.def findErrorNums(nums):
n = len(nums)
duplicate = -1
missing = -1
# Use a frequency array to track the occurrences of each number
count = [0] * (n + 1)
for num in nums:
count[num] += 1
for i in range(1, n + 1):
if count[i] == 2:
duplicate = i
elif count[i] == 0:
missing = i
return [duplicate, missing]
# Example usage:
nums = [1, 2, 2, 4]
print(findErrorNums(nums)) # Output: [2, 3]
n
is the length of the input array nums
.
1
to n
.This method ensures that we efficiently identify the duplicate and missing numbers using a straightforward approach.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?