寒假每日一题(day6)

这是我做题时第一版的想法,即先将数组按顺序排列,这样数组下标与数字就会有某种对应关系,然后先查重,再根据前后项的差值就可以找出缺失的数字,但是缺失数字在开头和结尾的两种情况容易漏掉,所以我们要单独陈列。 

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开始遍历。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值