leetcode刷题记录15

介绍15

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?

思路15

等差数列

代码15

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s=sum(nums)
n=max(nums)
if min(nums)!=0:
return 0
else:
if n*(n+1)/2-s==0:
return n+1
else:
return n*(n+1)/2-s