Easy Java Solution O(N)


  • 0
        public void nextPermutation(int[] nums) {
            int i,f;
            for(i=nums.length-1;i>0;i--){
                if(nums[i]>nums[i-1])break;
            }
            if(i!=0){
                for(f=nums.length-1;f>i;f--){
                    if(nums[i-1]<nums[f])break;
                }
                swap(nums,i-1,f);
            }
            for(int j=i;j<=(i+nums.length-1)/2;j++){
                swap(nums,j,nums.length-1-j+i);
            }
        }
        public void swap(int[] nums,int a,int b){
            int temp = nums[a];
            nums[a] = nums[b];
            nums[b] = temp;
        }

Log in to reply
 

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