Skip to content

Latest commit

 

History

History
146 lines (114 loc) · 2.51 KB

README_EN.md

File metadata and controls

146 lines (114 loc) · 2.51 KB

中文文档

Description

An array contains all the integers from 0 to n, except for one number which is missing.  Write code to find the missing integer. Can you do it in O(n) time?

Note: This problem is slightly different from the original one the book.

Example 1:

Input: [3,0,1]

Output: 2

 

Example 2:

Input: [9,6,4,2,3,5,7,0,1]

Output: 8

Solutions

Python3

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        res = 0
        for i, num in enumerate(nums):
            res = res ^ num ^ (i + 1)
        return res

Java

class Solution {
    public int missingNumber(int[] nums) {
        int res = 0;
        for (int i = 0; i < nums.length; ++i) {
            res = res ^ nums[i] ^ (i + 1);
        }
        return res;
    }
}

JavaScript

/**
 * @param {number[]} nums
 * @return {number}
 */
var missingNumber = function (nums) {
    let res;
    for (let i = 0; i < nums.length; i++) {
        res = res ^ nums[i] ^ (i + 1);
    }
    return res;
};

C++

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int res = 0;
        for (int i = 0; i < nums.size(); ++i) {
            res = res ^ nums[i] ^ (i + 1);
        }
        return res;
    }
};

Rust

impl Solution {
    pub fn missing_number(mut nums: Vec<i32>) -> i32 {
        nums.sort();
        let n = nums.len() as i32;
        for i in 0..n {
            if i != nums[i as usize] {
                return i;
            }
        }
        n
    }
}
impl Solution {
    pub fn missing_number(nums: Vec<i32>) -> i32 {
        let n = nums.len() as i32;
        let mut sum = 0;
        let mut max = 0;
        for num in nums {
            sum += num;
            max = max.max(num);
        }
        if max == n {
            ((1 + max) * max / 2) - sum
        } else {
            n
        }
    }
}
impl Solution {
    pub fn missing_number(nums: Vec<i32>) -> i32 {
        let mut res = 0;
        let n = nums.len();
        for i in 0..n {
            res ^= nums[i] ^ (i + 1) as i32;
        }
        res
    }
}

...