Very simple Java solution


  • 0
    B
    public class Solution {
        public int firstMissingPositive(int[] nums) {
            boolean restart = false;
            for(int i = 0; i < nums.length; i++) {
                if (nums[i] == i+1) {
                    if (restart) {
                        i = -1;
                        restart = false;
                    }
                } else if (nums[i] > nums.length || nums[i] < 1) {
                    if (restart) {
                        nums[i] = i+1;
                        i = -1;
                        restart = false;
                    } else {
                        nums[i] = 0;
                    }
                } else {
                    int tmp = nums[i];
                    if (restart) {
                        nums[i] = i+1;
                    } else {
                        nums[i] = 0;
                    }
                    i = tmp-1-1; //don't forget the ++ in the loop
                    restart = true;
                }
            }
            int i;
            for(i = 0; i < nums.length; i++) {
                if (nums[i] != i+1) return i+1;
            }
            return i+1;
        }
    }

Log in to reply
 

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