码迷,mamicode.com
首页 > 其他好文 > 详细

268. Missing Number

时间:2017-10-10 10:08:11      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:code   hat   array   tin   while   binary   mis   number   linear   

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?

 

1.XOR
public int missingNumber(int[] nums) { //xor
    int res = nums.length;
    for(int i=0; i<nums.length; i++){
        res ^= i;
        res ^= nums[i];
    }
    return res;
}
2.SUM
public int missingNumber(int[] nums) { //sum
    int len = nums.length;
    int sum = (0+len)*(len+1)/2;
    for(int i=0; i<len; i++)
        sum-=nums[i];
    return sum;
}
3.Binary Search
public int missingNumber(int[] nums) { //binary search
    Arrays.sort(nums);
    int left = 0, right = nums.length, mid= (left + right)/2;
    while(left<right){
        mid = (left + right)/2;
        if(nums[mid]>mid) right = mid;
        else left = mid+1;
    }
    return left;
}

  

268. Missing Number

标签:code   hat   array   tin   while   binary   mis   number   linear   

原文地址:http://www.cnblogs.com/apanda009/p/7643717.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!