268. Missing Number

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

For example,
Given nums = [0, 1, 3] return 2.

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

读题

题目的意思就是给你n个数,从0-n,找到缺失的那个数

思路

  • 一种是常规的思路,用0-n之和减去数组每个元素之和就是缺失的那个数

  • XOR的方式

The basic idea is to use XOR operation. We all know that abb =a, which means two xor operations with the same number will eliminate the number and reveal the original number.
In this solution, I apply XOR operation to both the index and value of the array. In a complete array with no missing numbers, the index and value should be perfectly corresponding( nums[index] = index), so in a missing array, what left finally is the missing number.

利用的公式就是a^b^b =a,如果一个数组里面没有元素是缺失的,那么元素的下标和元素是对应的

题解

public class Solution {
    public static int missingNumber(int[] nums) {
         int sum = nums.length*(nums.length+1)/2;
         int  m = 0;
         for(int i:nums) m+=i;
         return sum-m;
      } 
}

或者

public int missingNumber(int[] nums) {

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

你可能感兴趣的:(268. Missing Number)