Skip to content

Instantly share code, notes, and snippets.

@daoseng33
Created August 4, 2017 08:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daoseng33/05be37d9961995026d57f515d6872066 to your computer and use it in GitHub Desktop.
Save daoseng33/05be37d9961995026d57f515d6872066 to your computer and use it in GitHub Desktop.
/*
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.
*/
class Solution {
func findErrorNums(_ nums: [Int]) -> [Int] {
let sortedNums = nums.sorted()
var sum = 0
var sum2 = 0
var preNum = 0
var repeatNum = 0
for index in 0 ..< sortedNums.count {
sum += index + 1
sum2 += sortedNums[index]
if preNum == sortedNums[index] {
repeatNum = sortedNums[index]
}
preNum = sortedNums[index]
}
return [repeatNum, repeatNum + sum - sum2]
}
}
Solution().findErrorNums([1,5,3,2,2,7,6,4,8,9])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment