easy understanding bucket sort java method O(N) time, O(1) space


  • 0
    H

    ''''
    public int missingNumber(int[] nums) {
    if (nums == null || nums.length == 0) return 0;

        for (int n_i = 0; n_i < nums.length; n_i ++) {
            while (nums[n_i] != n_i && nums[n_i] != nums.length) {
                swap(nums, n_i, nums[n_i]);
            }
        }
        
        for (int n_i = 0; n_i < nums.length; n_i ++) {
            if (nums[n_i] == nums.length) return n_i;
        }
        return nums.length;
    }
    
    private void swap(int[] nums, int index1, int index2) {
        int tmp = nums[index1];
        nums[index1] = nums[index2];
        nums[index2] = tmp;
    }
    

    ''''


Log in to reply
 

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