FTPrep, 41 First Missing Positive

来源:互联网 发布:php soapclient https 编辑:程序博客网 时间:2024/04/29 12:21

TODO:

1. how to design, what is your target, to get the target how to design your program

2, 2 loop structure. 

3. key points, at least the 2 bad bugs!! in the quesiton, until 3rd time: one-time bug-free: 3’29“

这道题在面试中我真的遇到了! 有点tricky啊,当时我错误理解题意,没考虑到1,2,3,4,5这种连续递增的例子,就以为返回最小值,然后看最小值是不是1,naive了。

代码:

public class Solution {    public int firstMissingPositive(int[] nums) {        if(nums==null || nums.length==0) return 1;        int len=nums.length;        for(int i=0; i<len; i++){            if(nums[i]>=1 && nums[i]<=len && nums[i]!=nums[nums[i]-1]){            // bad bug: the condition cannot be: i!=nums[i]-1; otherwise [1,1] infi loop。!!value是目标,就一直用value来作为判断条件            // good thing: it points out the whole point of last statement, we must compare two elements and do not swap 2 same elements,             // otherwise it is a infi loop                int temp=nums[nums[i]-1]; // int temp=nums[i];                nums[nums[i]-1]=nums[i];  // nums[i]=nums[nums[i]-1];                nums[i]=temp;             // nums[nums[i]-1]=temp;                                // bad bug: read after write! nums[i] was modified before the 3rd step                i--; // 自己画图才搞得清楚为什么这里还要再次--,为了在下一个iteration,好要来check一遍。                // 因为不是一次就能swap到正确的值,再swap了之后还要继续checking,直到这个if的condtion不成立                // 那就是有两种情况:1,out of range [1,len];2,在range内,但是不符合规则。所以还要再次check            }        }        for(int i=0; i<len; i++){            if(nums[i]!=i+1) return i+1;        }        return len+1;    }}


关于最后return的注释,其实也是return i+1; 的因为出了loop后i就是 len,只是i 是local variable,所以没了。说这个的point是,这题的目的就是要构造出一个具有一下特点的array:nums[i]== i+1

总结:

// 最关键的就是for() loop的条件和内部的实现:1,始终以value作为判断条件,因为value是目标,同时也是index+1,有两层含义,所以可以通过 value来判断index的范围: nums[i] in the range of [1, len] && nums[i]!=nums[nums[i]-1];
// 2,内部的swap 当然是对判断的对象 nums[i] & nums[nums[i]-1] 进行判断啦,在swap之后并不能保证 换过来的nums[nums[i]-1]就 满足条件(换图举例可知[5,1,2,3,4]),所以还要i--,在下一个iteration重新进行判断。