My Java Solution


  • 0
    B
    public class Solution {
    public void nextPermutation(int[] nums) {
        for(int i=nums.length-2; i>=0; i--){
            if(nums[i]<nums[i+1]){
                int exc=i+1;
                for(int k=i+1; k<nums.length; k++){
                    if(nums[k]>nums[i] && nums[k]<nums[exc]) exc=k;
                }
                swap(nums,i, exc);
                Arrays.sort(nums, i+1,nums.length);
                break;
            }
            if(i==0) Arrays.sort(nums);
        }
    }
    public void swap(int[] nums, int index1, int index2){
        int temp=nums[index1];
        nums[index1]=nums[index2];
        nums[index2]=temp;
    }
    

    }


Log in to reply
 

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