位运算(4)——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?

排序后再找时间复杂度不合题意。

0……n异或,然后nums[i]异或:

 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 }

异或解决的题目还有 “有几个数,其中只有一个数有奇数个,其余的数有偶数个,找出奇数个的那个数”

posted @ 2017-05-25 15:52  D-Dong  阅读(230)  评论(0编辑  收藏  举报