Skip to content

Commit 2e36d61

Browse files
committed
add solution of problem 268: Missing number
1 parent 70d7486 commit 2e36d61

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

MissingNumber268/README.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
Given an array containing *n* distinct numbers taken from `0, 1, 2, ..., n`, find the one that is missing from the array.
2+
3+
For example,
4+
Given *nums* = `[0, 1, 3]` return `2`.
5+
6+
#####Note:
7+
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
8+
9+
10+
#####思路
11+
0、1、2....n之和expectedSum为(n+1)*n/2
12+
13+
拿掉一个数k后的和sum为(n+1)*n/2-k
14+
15+
因此k = expectedSum - sum

MissingNumber268/Solution.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
public class Solution {
2+
public int missingNumber(int[] nums) {
3+
if (nums == null || nums.length == 0)
4+
return 0;
5+
6+
int expectedSum = (nums.length + 1) * nums.length / 2;
7+
int sum = 0;
8+
for (int i = 0; i < nums.length; i++)
9+
sum += nums[i];
10+
11+
return expectedSum - sum;
12+
}
13+
}

0 commit comments

Comments
 (0)