268. Missing Number

来源:互联网 发布:威行通淘宝代运营如何 编辑:程序博客网 时间:2024/06/10 09:05

Given an array containing n distinct numbers taken from0, 1, 2, ..., n, find the one that is missing from the array.

Example 1

Input: [3,0,1]Output: 2

Example 2

Input: [9,6,4,2,3,5,7,0,1]Output: 8


Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

class Solution {    public int missingNumber(int[] nums) {        Arrays.sort(nums);        int left=0;        int right=nums.length;        int mid=(left+right)/2;        while(left<right){            mid=(left+right)/2;            if(nums[mid]>mid){                right=mid;            }else{                left=mid+1;            }        }        return left;    }}

二分法查找,如果nums[mid]>mid说明丢失的值在mid的左侧,只需要继续查找左边部分即可,故right=mid

class Solution {    public int missingNumber(int[] nums) {        int total = 0;        for(int i = 1; i <= nums.length ;i++ ){            total += i;        }        for(int n : nums){            total -= n;        }        return total;    }}
因为是等差序列,所以先将所有不缺失数值的总数值计算出来,减去目前存在的数值,剩下的就是目前丢失的值


原创粉丝点击