ITeye博客

Missing Number

KickCode · 2016-02-25 03:46 · Leetcode · 编程语言 · Markdown

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 = return 2.

通过位运算,将数组里面的元素与对应的下标进行异或运算,得到一个结果result, 然后将result与数组的长度进行异或运算,得到的结果就是缺少的数字。代码如下:


public class Solution {
    public int missingNumber(int[] nums) {
        if(nums == null) return -1;
        int result = 0;
        for(int i = 0; i < nums.length; i++) {
            result ^= i ^ nums[i];
        }
        return result ^ nums.length;
    }
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。