[数组]268. Missing Number

题目: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?

找到顺序数列0,1,2,...n 中缺失的一位。关键在于如何不使用额外空间。
排好序遍历即可。

class Solution {
    public int missingNumber(int[] nums) {
        if(nums == null) return 0;
        Arrays.sort(nums);
        for(int i = 0 ; i< nums.length ; i++){
            if( nums[i] != i){
                return i;
            }
        }
        return nums.length;
    }
}

你可能感兴趣的:([数组]268. Missing Number)