Joey LIU | NANTSOU


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
 * The key to check the next permutation is to check the values from right to left.
 */
class Solution {
    public void nextPermutation(int[] nums) {
        // use i to find the position where the value begins descending.
        // use j to find the position where the value is most close and grater than the one at i.
        int i = nums.length - 2, j = nums.length - 1;
        
        // find the position where the value begins descending.
        while (i >= 0 && nums[i] >= nums[i + 1]) i--;

        // i could become -1 when there are duplicates in nums and no descending point.
        // thus, i >= 0 is needed to be checked.
        if (i >= 0) {
            // find the position where the value is most close and grater than the one at i.
            while (nums[j] <= nums[i]) j--;
            swap(nums, i, j);
        }
        
        // After swap the i and j, the elements after i need to be reverse to ascending order.
        reverse(nums, i + 1, nums.length - 1);
    }
    
    private void swap(int[] nums, int i, int j) {
        nums[i] = nums[i]^nums[j];
        nums[j] = nums[i]^nums[j];
        nums[i] = nums[i]^nums[j];
    }
    
    private void reverse(int[] nums, int i, int j) {
        while (i < j) {
            swap(nums, i, j);
            i++;
            j--;
        }
    }
}