Simple Java solution for your reference


  • 6
    T
    public void nextPermutation(int[] num) {
        for(int i = num.length-1; i > 0; i--) {
            if(num[i-1] < num[i]) {
                Arrays.sort(num, i, num.length);
                for(int j = i; j < num.length; j++) {
                    if(num[j] > num[i-1]) {
                       // swap num[i-1] and num[j]
                        num[i-1] = num[i-1] + num[j];
                        num[j] = num[i-1] - num[j];
                        num[i-1] = num[i-1] - num[j];
                        return;
                    }
                }
            }
        }
        Arrays.sort(num);
    }

  • 0
    R

    Very good Solution


  • 0
    J

    Since nums array is definitely descending order when you call arrays#sort, you would better implement your own reverse function rather than sort to reduce your runtime.

        public void reverse(int[] nums, int from, int to) {
        int len = to - from;
        for (int i=0; i<len/2; i++) {
            int temp = nums[from+i];
            nums[from+i] = nums[to-1-i];
            nums[to-1-i] = temp;
        }
        }

Log in to reply
 

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