Java O(nlogn) sulution. Ituitive. Using sorting.


  • 0
    F

    public int[] findErrorNums(int[] nums) {

    /* Sort the array /
    Arrays.sort(nums);
    int[] result = new int[2];
    int difference=0;
    /
    Do a full loop, sum all numbers from 1 to n, and minus the sum of the wrong nums array.
    * We get the difference between the duplicate number and the missing number.
    * Add the difference to the duplicate number /
    for(int i=0;i<nums.length-1;i++)
    {
    /
    if there are two consecutive same numbers, it is the wrong one /
    if(nums[i]==nums[i+1]){
    result[0]=nums[i];
    }
    difference += i+1; /
    Avoid overflow /
    difference-=nums[i];
    }
    difference = difference + nums.length - nums[nums.length-1]; /
    add and minus the last number */
    result[1]=result[0]+difference;
    return result;
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.