268 Missing Number

268 Missing Number


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



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

 

Given an array containing n distinct numbers taken from 0, 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

posted on 2018-08-09 18:40  猪猪&#128055;  阅读(139)  评论(0)    收藏  举报

导航