这是我做题时第一版的想法,即先将数组按顺序排列,这样数组下标与数字就会有某种对应关系,然后先查重,再根据前后项的差值就可以找出缺失的数字,但是缺失数字在开头和结尾的两种情况容易漏掉,所以我们要单独陈列。
class Solution {
public int[] findErrorNums(int[] nums) {
quicksort(nums);
int[] matrix=new int[2];
for (int i=0;i<nums.length;i++){
if (nums[i]==nums[i+1]){
matrix[0]=nums[i];
break;
}
}
if(nums[0]==2){
matrix[1]=1;
return matrix;
}
for (int i=0;i<nums.length-1;i++){
if(nums[i+1]-nums[i]>1){
matrix[1]=nums[i]+1;
return matrix;
}
}
if (nums[nums.length-1]!=nums.length){
matrix[1]=nums.length;
return matrix;
}
return nums;
}
public static void swap(int[] arr,int x,int y){
int temp=arr[x];
arr[x]=arr[y];
arr[y]=temp;
}
public static void subSort(int[] num,int start,int end){
if (start<end) {
int low=start;
int high=end+1;
int key=num[start];
while (true){
while (low<end && num[++low]-key<=0);
while (high>start && num[--high]-key>=0);
if(high>low){
swap(num,low,high);
}else {
break;
}
}
swap(num,start,high);
subSort(num,start,high-1);
subSort(num,high+1,end);
}
}
public static void quicksort(int[] num){subSort(num,0,num.length-1);}
}
第一版虽然能运行但是运行速度极慢,而且消耗内存大,所以我改了这个第二版。
class Solution {
public int[] findErrorNums(int[] nums) {
int[] matrix=new int[2];
int[] Account=new int[nums.length+1];
for (int i=0;i<nums.length;i++){
Account[nums[i]]++;
}
for (int i=1;i<nums.length+1;i++){
if (Account[i]==2){
matrix[0]=i;
}
if (Account[i]==0){
matrix[1]=i;
}
}
return matrix;
}
}
第二版中,我们用一个新的数组来储存原数组中每个数字出现的次数,然后遍历新数组,如果次数为2就是重复,如果次数为0就是缺失,要注意,遍历新数组时要从1开始遍历。