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.
出現(xiàn)了數(shù)值和索引一致,并且各異這種極好的條件,所以可以考慮索引排序。
問題是怎么寫索引排序。在所有數(shù)都不同的情況下,考慮到每個數(shù)值都會對應(yīng)唯一一個索引,如果在原來數(shù)組的位置I-1上對應(yīng)的NUMS[I]!=i-1,那么明顯的nums[i]應(yīng)該被放到nums[i]-1上去,此時數(shù)組[nums[i]-1]位置上肯定也有一對這樣的不匹配(因為nums[i]應(yīng)該被放在nums[i]-1的位置上,由各異可以知道這個位置上只能有一個,明顯的現(xiàn)在nums[i]-1位置上的數(shù)不是nums[i])。換句話說,對于沒有重復(fù)值只存在1.兩個位置上的數(shù)都不符合條件。2.兩個位置上的數(shù)都符合條件,這兩種情況。
現(xiàn)在,出現(xiàn)了重復(fù)元素,出現(xiàn)了第三種情況,即一個符合,一個不符合。這種情況,只有在這個元素是重復(fù)元素時才會出現(xiàn)。所以我們直接跳過元素就好了
注意在swap時一定要保證交換以后一定是num[i]=i+1,數(shù)組滿足排定,所以用的whlle循環(huán)。
class Solution {
public int[] findErrorNums(int[] nums) {
int[] result= new int[2];
for(int i = 0 ;i<nums.length;i++)
{
while(nums[i]!=i+1&&nums[nums[i]-1]!=nums[i])
swap(nums,i,nums[i]-1);
}
// 排定數(shù)組
for(int i = 0 ;i<nums.length;i++)
{
if(nums[i]!=i+1)
{
result[0]=nums[i];
result[1]=nums[i+1];
}
return result;
}
private void swap (int[] nums,int i ,int j )
{
int temp =nums[i];
nums[i]=nums[j];
nums[j]=temp;
}
}
排序后遍歷找到第一個不滿足條件的數(shù)。