One loop simple java solution with comments


  • 1
    S
    public class Solution {
        public void nextPermutation(int[] nums) {
            int len = nums.length;
            int index = -1;
            //find out the index that is not ascending from right most
            for(int i=len-2; i>=0; i--) {
                if(nums[i] < nums[i+1]) {
                    index = i; break;
                }
            }
            if(index == -1) Arrays.sort(nums);
            else {
                //sort the right part of index and swap the index with the min of nums bigger than nums[index] in the right part
                Arrays.sort(nums, index+1, len);
                for(int i=index+1; i<len; i++) {
                    if(nums[i] > nums[index]) {
                        swap(nums, i, index);
                        break;
                    }
                }
            }
        }
        
        public void swap(int[]nums, int i, int j) {
            int tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }
    }

Log in to reply
 

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