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