We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
0, 1, 2, ..., n
For example, Given nums = [0, 1, 3] return 2.
[0, 1, 3]
2
Note: Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
代码的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); } }
用int也行,测试用例不会溢出。
int
The text was updated successfully, but these errors were encountered:
No branches or pull requests
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]
return2
.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)。
代码如下所示:
Analysis
用
int
也行,测试用例不会溢出。The text was updated successfully, but these errors were encountered: