標籤:extra int wap 就是 etc swap vat ... set
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; }}
leetcode268 - Missing Number - easy