Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode-268: Missing Number #18

Open
zeqing-guo opened this issue Nov 5, 2015 · 0 comments
Open

Leetcode-268: Missing Number #18

zeqing-guo opened this issue Nov 5, 2015 · 0 comments

Comments

@zeqing-guo
Copy link
Owner

Missing Number

Description

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?

My Solution

代码的run time是1 ms,代码的时间复杂度是O(n),空间复杂度是O(1)。
代码如下所示:

public class Solution {
    public int missingNumber(int[] nums) {
        if (nums == null) {
            return 0;
        }

        long len = nums.length;
        long sumOfNums = 0;

        for (int num : nums) {
            sumOfNums += num;
        }

        long sumOfArray = len * (len + 1) >> 1;

        return (int) (sumOfArray - sumOfNums);
    }
}

Analysis

int也行,测试用例不会溢出。

@zeqing-guo zeqing-guo changed the title Leetcode-35: Search Insert Position Leetcode-268: Missing Number Nov 5, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant