Description
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
1 2Input: [1,2,0] Output: 3Example 2:
1 2Input: [3,4,-1,1] Output: 2Example 3:
1 2Input: [7,8,9,11,12] Output: 1Note:
- Your algorithm should run in O(n) time and uses constant extra space.
使用O(n)的时间复杂度和O(1)的空间在无序数组中查找第一个缺失的正数。
Solution
此题关键在于利用数字直接寻找其位置,达到排序目的。
假设有数组[4, 3, 5, 1]:
取第一个数4,检查4是否在第4个位置:否,与第四个位置数字交换得到[1, 3, 5, 4]。
交换后继续判断当前数字1是否在第1个位置:是,则跳过。
依次判断之后得到数组[1, 5, 3, 4]。其中遇到5时因为其超过数组长度,直接跳过。
再次从第一个位置开始判断,找到第一个位置与数字不符合的地方即为缺失的数字。
| |