Missing figures

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 solve this problem with a linear time complexity algorithm that only uses extra constant space?

Examples can be found on the LeetCode website.

Source: LeetCode link: leetcode-cn.com/problems/mi… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Solution 1: array traversal

Sum = sum (n *(n+1)/2) sum = sum (n *(n+1)/2) sum = sum (n *(n+1)/2) sum = sum (n *(n+1)/2)

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)); }}Copy the code

The most clear footprints are always printed on the muddy road.