Leetcode 645(Java)

来源:互联网 发布:jessyline姐妹品牌js 编辑:程序博客网 时间:2024/05/16 17:40

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,则可以认为是一个a1=1,项数为n的等差数列。先用等差数列求和公式计算出正确数组所得之和。再建立一个boolean型的数组用于标记一个元素是否出现过。遍历数组改变所遍历元素在boolean型数组里的对应下标,同时计算当前数组的和。遍历完毕后找出下标为false的元素,+1即为所缺少元素,又比较应得之和与当前数组和可以得出重复元素与缺失元素之间的差距。放入result中即可,ac码如下:

    public int[] findErrorNums(int[] nums) {        int[] result  = new int[2];        int n = nums.length;        int sum = n+n*(n-1)/2;        int sum1=0;         int index=0;        boolean[] copy = new boolean[n];        for(int i=0;i<n;i++){            copy[nums[i]-1]=true;            sum1+=nums[i];        }        for(int i=0;i<n;i++){            if(copy[i]==false){                result[1]=i+1;                index=i+1;            }        }        if(sum1>sum){            result[0]=index+sum1-sum;        }else{            result[0]=index-(sum-sum1);        }        return result;        }
原创粉丝点击