算法系列——Missing Number

来源:互联网 发布:1hhhh.com域名升级访问 编辑:程序博客网 时间:2024/06/07 04:05

题目描述

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之间少了一个数,我们将这个少了一个数的数组合0到n之间完整的数组异或一下,那么相同的数字都变为0了,剩下的就是少了的那个数字了。

求和

也可以利用求和公式,算出 0-n的和,然后将数组求和,做差即可。
代码不再给出。

程序实现

public class Solution {    public int missingNumber(int[] nums) {        int len=nums.length;        int XOR=0;        for(int i=0;i<=len;i++)            XOR^=i;        for(int val:nums)            XOR^=val;        return XOR;    }}
原创粉丝点击