2
头图

Missing numbers

Title description: Given an array nums containing n numbers in [0, n], find the number in the range [0, n] that does not appear in the array.

Advanced:

  • Can you achieve linear time complexity and only use an extra constant space algorithm to solve this problem?

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/missing-number/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution one: array traversal
First, get the length of the number as n. According to the formula n*(n+1)/2 , the sum of the numbers from 0 to n is sum. Since there is only one number missing in the nums array, we traverse the array and subtract all the elements in the array from sum. Then the remaining number is the number to be returned.
public class LeetCode_268 {
    public static int missingNumber(int[] nums) {
        int n = nums.length;
        int sum = n * (n + 1) / 2;
        for (int num : nums) {
            sum -= num;
        }
        return sum;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{9, 6, 4, 2, 3, 5, 7, 0, 1};
        System.out.println(missingNumber(nums));
    }
}
[Daily Message] The clearest footprints are always printed on the most muddy road.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!