Leetcode_Array -- 268. Missing Number [easy]
阿新 • • 發佈:2018-12-17
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
給定一個包含n個不同的數字的陣列,找到這個陣列中從0到n缺少的數
這裡需要解釋一下n個數的陣列只能裝下n-1個數!即三個數的組數[3,1,2],其缺少的數字是0。
Example 1:
Input: [3,0,1]
Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
Solutions:
Python (1) class Solution: def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ length = len(nums) newnums = list(range(length+1)) #建立一個包含n+1個排好序的列表 numssort = sorted(nums) #將原陣列排序 for i in range(len(nums)): #對比排好序的原陣列和建立好的n+1陣列 if newnums[i] != numssort[i]: #如果兩個數不相同,那麼說明少了newnums[i]這個數 return newnums[i] return newnums[length] #如果遍歷完nums之後,說明少了最大的第n個數,所以返回newnums[length] (2) class Solution: def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ #這個方法更加簡單,先求n個數的加和,再求原陣列的加和,兩者差值即為缺少的元素 n = len(nums) expected_sum = n*(n+1)/2 actual_sum = sum(nums) return expected_sum-actual_sum
C++ #include <numeric> //呼叫加和函式accumulate需要用到函式庫numeric class Solution { public: int missingNumber(vector<int>& nums) { int length = nums.size(); int exp = length*(length+1)/2; //必定整除,因為length和length+1必定一個奇數一個偶數 int sum = accumulate(nums.begin(),nums.end(),0); //accumulate帶有三個形參:前兩個形參指定要累加的元素範圍,第三個形參則是累加的初值。 return exp-sum; } };