AviatorJeremy

[leetcode268]Missing Number

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

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

 

解法考虑两种:数学解法和数组解法,数学解法利用连续n个数的序列特点,求和后求差计算,O(n)时间复杂度

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

  

posted on 2018-09-11 17:12  AviatorJeremy  阅读(110)  评论(0编辑  收藏  举报

导航