645. Set Mismatch #
Problem #
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.
Problem Summary #
Set S contains the integers from 1 to n. Unfortunately, due to a data error, one element in the set was copied and became the value of another element in the set, causing the set to lose one integer and have one repeated element. Given an array nums representing the result after the error occurred in set S. Your task is to first find the integer that appears twice, then find the missing integer, and return them in the form of an array.
Note:
- The length of the given array is in the range [2, 10000].
- The given array is unordered.
Solution Approach #
- Given an array containing the numbers 1-n, due to an error, one number became another number. The task is to find the repeated number and the correct missing number. This is an easy problem; by comparing based on indices, you can find which number is repeated and which number is missing.
Code #
package leetcode
func findErrorNums(nums []int) []int {
m, res := make([]int, len(nums)), make([]int, 2)
for _, n := range nums {
if m[n-1] == 0 {
m[n-1] = 1
} else {
res[0] = n
}
}
for i := range m {
if m[i] == 0 {
res[1] = i + 1
break
}
}
return res
}