Next Permutation & Previous Permutation

时间:2023-03-09 18:21:02
Next Permutation & Previous Permutation

Next Permutation

Given a list of integers, which denote a permutation.

Find the next permutation in ascending order.

Notice

The list may contains duplicate integers.

Example

For [1,3,2,3], the next permutation is [1,3,3,2]

For [4,3,2,1], the next permutation is [1,2,3,4]

Analysis:

In order to find the next permutation, we need to begin from the right most and find a number which is less than its right neighbor. And then switch it with the smallest number on its right side, but that smallest number must be greater than the number to be switched.

 class Solution {
public void nextPermutation(int[] nums) {
int i = nums.length - ;
// 从最右边开始,首先找到一个值而且该值比它右边那个更小,这样我们可以把该值和它右边最小的值交换。
// example: 1329876, the next one is 1362789
while (i >= && nums[i + ] <= nums[i]) {
i--;
}
if (i >= ) {
int j = nums.length - ;
// we need to find the min value from i + 1 to j which is greater than nums[i]
while (j >= && nums[j] <= nums[i]) {
j--;
}
swap(nums, i, j);
}
reverse(nums, i + );
} private void reverse(int[] nums, int start) {
int i = start, j = nums.length - ;
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
} private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}

Previous Permutation

Given a list of integers, which denote a permutation.

Find the previous permutation in ascending order.

Notice

The list may contains duplicate integers.

Example

For [1,3,2,3], the previous permutation is [1,2,3,3]

For [1,2,3,4], the previous permutation is [4,3,2,1]

Analysis:

From the right most, find a number which is greater than its right neighbor, then switch it with the largest number on its right side, but that largest number must be less than the number to be switched.

 public class Solution {
/**
* @param nums: A list of integers
* @return: A list of integers that's previous permuation
*/
public ArrayList<Integer> previousPermuation(ArrayList<Integer> numss) { if (numss == null || numss.size() <= )
return numss; Integer[] nums = new Integer[numss.size()];
numss.toArray(nums); int k = nums.length - ; while (k >= && nums[k] <= nums[k + ]) {
k--;
}
// test case 211189
if (k != -) {
int p = nums.length -;
while (p > k) {
if (nums[k] > nums[p]) {
swap(nums, k, p);
break;
}
p--;
}
swapAll(nums, k + , nums.length - );
} else {
swapAll(nums, , nums.length - );
}
return new ArrayList<Integer>(Arrays.asList(nums));
} public void swap(Integer[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
} public void swapAll(Integer[] nums, int i, int j) {
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}
}