Description:
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.
题意:给定一个数组,包含元素[1,n],其中仅有一个元素出现两次,一个元素出现0次,要求找出出现两次和出现0次的元素;
解法:既然已经说明了数组中的元素是在范围[1,n]内的,那么我们可以对数组中元素对应的下标进行标记,例如对于元素2,我们标记数组下标位置1处,表明元素2出现过,这里因为元素都是正数,因此,我们令元素取负来标记;
举个例子:
给定数组arr = [4,2,2,1]
- 对于第一个元素1,为了标记他,我们令arr[Math.abs(arr[0]) - 1] *= -1(即arr[3] = -1),得到arr = [4,2,2,-1]
- 对于第二个元素2,令arr[Math.abs(arr[1] - 1) *= -1(即arr[1] = -2),得到arr = [4,-2,2,-1]
- 对于第三个元素,因为arr[Math.abs(arr[2] - 1) < 0,说明这个元素出现了两次
- 对于第四个元素,令arr[Math.abs(arr[3]) - 1) *= -1(即arr[0] = -4),得到arr = [-4,-2,2,-1]
我们最后再遍历得到的数组,数组中为正数的那个所在的位置,说明那个元素没有出现过,即元素3;
Java
class Solution {
public int[] findErrorNums(int[] nums) {
int twiceNum = -1;
int misNum = -1;
for (int i = 0; i < nums.length; i++) {
if (nums[Math.abs(nums[i]) - 1] < 0) {
twiceNum = Math.abs(nums[i]);
} else {
nums[Math.abs(nums[i]) - 1] *= -1;
}
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) {
misNum = i + 1;
break;
}
}
return new int[] {twiceNum, misNum};
}
}