index based easy to understand Java solution


  • 0
    T
    public class Solution {
        public int firstMissingPositive(int[] nums) {
            if (nums.length == 0) {
                return 1;
            }
            int maxIdx = 0;
            for (int num : nums) {
                maxIdx = Math.max(maxIdx, num);
            }
            int[] bucket = new int[maxIdx + 2];
            for (int num : nums) {
                if (num > 0) {
                    bucket[num] = 1;
                }
            }
            int res = -1;
            for (int i = 1; i < bucket.length; i++) {
                if (bucket[i] == 0) {
                    res = i;
                    break;
                }
            }
            return res;
        }
    }
    

Log in to reply
 

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