LeetCode 268. 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 这 n+1 个数中的 n 个,这 n 个数不重复,乱序的在数组中存放,求出数组中不包含的那个数字。

解法一:

数学方法:我们知道 0 ~ n 这 n+1 个数之和,减去数组各元素即得到最后的Missing Number

代码:

public class Solution {
    public int missingNumber(int[] nums) {
        int n = nums.length;
        int result = n*(n + 1)/2;
        for(int i = 0; i < n; i++){
            result -= nums[i];
        }
        return result;
        
    }
}
解法二:

位运算:0 ~ n 这 n+1 个数异或所得的数 与 数组各元素异或所得的数 不同就在于 Missing Number,那么可以通过两个和的异或(XOR)获得

代码:

public class Solution {
    public int missingNumber(int[] nums) {
        
        int totalXOR = 1;
        int numsXOR = nums[0];
        for(int i = 1; i < nums.length; i++){
            numsXOR = nums[i] ^ numsXOR;
        }
        for(int i = 2; i <= nums.length; i++){
            totalXOR = i ^ totalXOR;
        }
        return numsXOR ^ totalXOR;
                
    }
}
解法三:

将数组中的元素排序,遍历数组,索引值与当前元素值相等则继续,索引值和当前元素值不同,则返回;如果全部相同,则返回索引的下一个值。

[0,1,2,3,5]-->返回4;[0,1,2,3,4]-->返回5.

代码:

public class Solution {
    public int missingNumber(int[] nums) {
        
        Arrays.sort(nums);
        int index;
        for(index = 0; index < nums.length; index++){
            if(index != nums[index]){
                return index;
            }
        }
        return index;
    }
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值