Straightforward Java Solution through Bucket_Sort


  • 0
    K

    public class Solution {

    public int firstMissingPositive(int[] nums) {
        bucket_sort(nums, nums.length);
        
        for (int i = 0; i < nums.length; i++) {
            
            if (nums[i] != (i + 1)) return i + 1;
        }
        
        return nums.length + 1;
    }
    
    public void bucket_sort(int[] nums, int len) {
        for (int i = 0; i < len; i++) {
            while (nums[i] != i + 1) {
                if (nums[i] <= 0 || nums[i] > len || nums[i] == nums[nums[i] - 1]) break;
                swap(nums, i, nums[i] - 1);
            }
        }
    }
    
    private void swap(int[] A, int i, int j){
        int temp = A[i];
        A[i] = A[j];
        A[j] = temp;
    }
    

    }


Log in to reply
 

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