Short Java 8, using reduce to find the duplicate


  • 0
    public int[] findErrorNums(int[] nums) {
            int n = nums.length;
            Arrays.sort(nums);
            int dupe = IntStream.range(1, n).boxed().reduce(new int[]{nums[0], nums[0]}, (acc, b) -> acc[0] == nums[b] ? new int[]{nums[b], nums[b]} : new int[]{nums[b], acc[1]}, (x, y) -> x)[1];
            int missing = n * (n + 1) / 2 - (Arrays.stream(nums).sum() - dupe);
            return new int[]{dupe, missing};
        }
    

Log in to reply
 

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