algorithm notes: leetcode#268 missing number

Problem


Solution


Analysis

Python implementation

1
2
3
4
5
6
7
8
class :
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
return n*(n+1)//2 - sum(nums)

Java implementation

1
2
3
4
5
6
7
8
9
10
class {
public int missingNumber(int[] nums) {
int n = nums.length;
int sum = 0;
for(int num : nums){
sum += num;
}
return n*(n+1)/2 - sum;
}
}

Time complexity

O(N).

Space complexity

O(1).


268. Missing Number
(中文版) 算法笔记: 力扣#268 缺失数字