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;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容