Missing Number(leetcode268)

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.git

Example 1:github

Input: [3,0,1]
Output: 2

Example 2:spa

Input: [9,6,4,2,3,5,7,0,1]
Output: 8

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?code

//正常思惟就會想到 正常數據該有的樣子減去已有數據
public static int missingNumber(int[] nums) {
        int sum = Arrays.stream(nums).sum();
        int assumeSum = nums.length*(nums.length+1)/2;
        return assumeSum-sum;
}

 

//別人寫的代碼 就是一下看不懂的
public static int missingNumber2(int[] nums) {

    int xor = 0, i = 0;
    for (i = 0; i < nums.length; i++) {
        xor = xor ^ i ^ nums[i];
    }

    return xor ^ i;
}

git:https://github.com/woshiyexinjie/leetcode-xinleetcode

相關文章
相關標籤/搜索