此次的题目之因此说是难,其实仍是在于对于某些空间和时间的限制。java
读了题目咱们或许还不理解题意,实际上是说正常的数组应该是[1,2,3,4....]这样的数组,或者打乱次序的,可是对于不是这样的数组,咱们须要从中找到从那个数字开始缺乏的,这个数字就是最小的数字,好比2,3,4,那么缺乏的就是1。好比1,2,4,就是少了3。这样咱们就理解了。可是时间复杂度要求O(n),空间使用是常数级别的。数组
咱们仔细思考一下,其实下标和这个是有关系的,正常的,最终均可以变成num[i]=i+1,因而咱们能够将数组进行一边扫描,若是已经知足这种性质的不用动,若是num[i]的值小于1或者大于长度的都是不该该存在的,所以置为一个标志,便于之后报错。若是在范围以内的,咱们就让它们物归原位。好比num[i]=x,那么这个元素应该在下标为x-1的位置上,所以咱们将num[x-1]和num[i]上的元素进行交换。交换的时候若是发现这两个值相等,则将非本位的值置为零,否者直接交换。this
class Solution { // let's rearrange the numbers in the array between 1 and length // in order (in place), leaving a 0 for numbers not present, // and ignoring the numbers out of this range. // then in second pass find the first zero occurence, or if none, // return length+1 // for example, [3,4,-1,1] will become [1,0,3,4] public int firstMissingPositive(int[] nums) { for (int i=0; i<nums.length;) { int n = nums[i]; if (n<1 || n>nums.length) { nums[i]=0; // out of range, remove i++; } else if (n-1==i) { i++; // in range and in position, leave as is } else { // in range but not in position, swap int temp = nums[n-1]; nums[n-1]=n; nums[i]=(temp==n)?0:temp;//这里最妙的就是没有i++,以此确保下一次还从这个地方开始 } } for (int i=0; i<nums.length; i++) { if (nums[i]==0) return i+1; } return nums.length+1; } }
遇到问题须要和实际的条件相联系,另外须要认真的判断全部的可能。spa