Given an array containing n distinct numbers taken from
0, 1, 2, ..., n
, find the one that is missing from the array.spaFor example,
Given nums =[0, 1, 3]
return2
.codeNote:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?blog
排序後再找時間複雜度不合題意。排序
0……n異或,而後nums[i]異或:it
1 public class Solution { 2 public int missingNumber(int[] nums) { 3 int n = nums.length; 4 int res = 0; 5 for(int i=1; i<=n; i++) { 6 res = res ^ i; 7 } 8 for(int i=0; i<n; i++) { 9 res = res ^ nums[i]; 10 } 11 return res; 12 } 13 }
用異或解決的題目還有 「有幾個數,其中只有一個數有奇數個,其他的數有偶數個,找出奇數個的那個數」io