My simple java solution


  • 0
    public class Solution {
        public void nextPermutation(int[] nums) {
            int len = nums.length;
            int index = len - 1;
            while (index > 0) {
                if (nums[index - 1] < nums[index]) {
                    swap(nums, index, len - 1);
                    int threshold = index;
                    int tmp = nums[index - 1];
                    while (threshold < len) {
                        if (nums[threshold] > tmp) {
                            nums[index - 1] = nums[threshold];
                            nums[threshold] = tmp;
                            break;
                        }
                        threshold++;
                    }
                    break;
                }
                index--;
            }
    
            //If there is no next permutation, rearrange to the lowest.
            if (index == 0) {
                swap(nums, 0, len - 1);
            }
        }
    
        public void swap(int[] nums, int start, int end) {
            while (start < end) {
                int tmp = nums[start];
                nums[start] = nums[end];
                nums[end] = tmp;
                start++;
                end--;
            }
        }
    }

Log in to reply
 

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