Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0] Output: 3
Example 2:
Input: [3,4,-1,1] Output: 2
Example 3:
Input: [7,8,9,11,12] Output: 1
Note:
Your algorithm should run in O(n) time and uses constant extra space.
题意:
给定一个无序的整数数组nums,找出数组中缺少的最小的正整数。另外 题目还要求算法时间复杂度为O(n),空间复杂度为常数级;
分析:
看到题目第一种想法是使用hash,即对每个大于0的元素做一次映射,最后在映射表中从1开始找到最先确实的元素即为数组缺少的最小正整数了。但是这种解法时间复杂度最差为O(n+n),即时间复杂度可以符合要求,但是使用hash的空间复杂度也是O(n),因此 此种解法无效。
下面是第二种思路,也是本题的最优解;
- 分析题意可知,假设数组长度为len,那