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?
开场暖身算法:排序后找O(logn), O(1)。hashSet先全加进去再一个个删看剩下的O(n), O(n)。
最优算法:桶排序思想。 O(n), O(1)。
本题假设数字应该呆的index就是数字本身。第一次扫描把所有数字换到自己应该呆的位置上。第二次扫描哪个位置上出现了错误的数字,那么期待的那个数字就是丢失的数字。(如果所有位置上都对了,那丢的是最后那个数字)。
类似题目:first missing positive。https://www.cnblogs.com/jasminemzy/p/9654890.html
实现:
class Solution { public int missingNumber(int[] nums) { for (int i = 0; i < nums.length; i++) { while (nums[i] != i && nums[i] < nums.length) { swap(nums, i, nums[i]); } } for (int i = 0; i < nums.length; i++) { if (nums[i] != i) { return i; } } return nums.length; } private void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }