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.
解题思路:
这道题可以通过求这两个数的差和他们的平方差来求解得到两个答案,但是题目要求的是先输出重复的数字,再输出缺失的数字,所以我们要判断他们的差是否大于0
解题代码:
ans=[0,0]
sub=subsquare=0
for i, num in enumerate(nums):
sub+=i+1-num
subsquare+=(i+1)**2-num**2
ans[0]=(subsquare/sub-sub)/2
ans[1]=sub+ans[0]
ans.sort()
if sub>0:
return ans
return ans[::-1]