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]

本文介绍了一种高效算法,用于解决数据集中一个数字重复而另一个数字缺失的问题。通过计算差值和平方差值,该算法能准确找到重复的数字和缺失的数字,并确保输出顺序符合题目要求。
413

被折叠的 条评论
为什么被折叠?



