LeetCode 268. Missing Number

本文介绍了一种算法问题:在一个包含0到n的整数数组中找到缺失的数字。提供了三种解决方案:通过累加求和确定缺失值;利用异或运算特性找到缺失数字;以及通过排序后使用二分查找的方法定位缺失值。

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?

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.


【题目分析】

从0,1,2,...,n这n+1个数中选择n个数,找出这n个数中缺失的那个数。


【思路】

1. 累加

计算1+2+...+n. 用和值减去数组中数的和值,最后的差就是我们要的结果。这个过程中要防止溢出。

2. 异或

异或运算有一个性质,x^y^y=x. 结果与x和y的顺序无关。我们把0~n与数组中的数都异或到一起,那么最后的结果就是缺失的那个数。

3. 二分查找

把数组排序,用二分查找来找到缺失值。


【java代码1】

 1 public class Solution {
 2     public int missingNumber(int[] nums) {
 3         int res = 0;
 4         for(int i = 1; i <= nums.length; i++) {
 5             res += (i-nums[i-1]);
 6         }
 7         
 8         return res;
 9     }
10 }

【java代码2】

1 public int missingNumber(int[] nums) { //xor
2     int res = nums.length;
3     for(int i=0; i<nums.length; i++){
4         res ^= i;
5         res ^= nums[i];
6     }
7     return res;
8 }

【java代码3】

 1 public int missingNumber(int[] nums) { //binary search
 2     Arrays.sort(nums);
 3     int left = 0, right = nums.length, mid= (left + right)/2;
 4     while(left<right){
 5         mid = (left + right)/2;
 6         if(nums[mid]>mid) right = mid;
 7         else left = mid+1;
 8     }
 9     return left;
10 }

 

 

转载于:https://www.cnblogs.com/liujinhong/p/6490254.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值