Java Simple Solution

  • 1
    public class Solution {
        public int firstMissingPositive(int[] nums) {
            //the range of the FMP must be within 1~len+1.
            int len = nums.length;
            int index=0;
            int i=0;
                if(nums[i]>=1 && nums[i]<=len && nums[nums[i]-1]!=nums[i]){
                    int tmp = nums[nums[i]-1];
                    nums[nums[i]-1] = nums[i];
                    nums[i] = tmp;
                } else i++;
            int res = 1;
            for(int j=0;j<len;j++){
                if(nums[j]==res) res++;
            return res;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.