leetcode 268. Missing Number
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
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?
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() n = len(nums) for i in range(0, n): if nums[i] != i: return i return n
自己写排序的话:
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ # [3,0,1] # 3 != nums[3-1], swap, [1, 0, 3] # 1 == nums[1-1] # 0 pass # 3 == nums[3-1] # [9,6,4,2,3,5,7,0,1] for i in xrange(0, len(nums)): while nums[i] != 0 and nums[i] != nums[nums[i]-1]: nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1] for i in xrange(0, len(nums)): if nums[i] != i+1: return i+1 return 0
对于1~n的数字排序,直接O(n)可以搞定哇!
利用数学知识搞定:
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) return n*(n+1)/2-sum(nums)
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ xor = len(nums) for i,n in enumerate(nums): xor = xor^n^i return xor
还有使用二分搞定:
class Solution { // Binary Search public int missingNumber(int[] nums) { //binary search Arrays.sort(nums); int left = 0, right = nums.length, mid= (left + right)/2; while(left<right){ mid = (left + right)/2; if(nums[mid]>mid) right = mid; else left = mid+1; } return left; } }