title: Algorithm small practice - a successive arrangement
DATE: 2019-12-19 19:55:01
the Categories:
- Algorithms
tags: - medium
Next arrangement
description
Achieve a function of the acquired arrangement, a given algorithm requires rearranging the sequence number next in lexicographically larger arrangement.
If the next larger arrangement does not exist, the smallest number of rearranged alignment (i.e., ascending order).
You must place editing, allowing only constant additional space.
Examples
The following are some examples, the input column on the left, on the right column the corresponding output.
→ 1, 3,2, 2, 3
3,2,1 →, 2, 3
1,1,5 1,5,1 →
Code reference
class Solution {
public void nextPermutation(int[] nums) {
int i = nums.length -2;
while (i>=0 && nums[i+1] <=nums[i]){ //从后往前循环判断整个数组,找到前一个数比后一个数大的 nums[i]
i--;
}
if(i>=0){
int j = nums.length - 1;
while (j>=0 && nums[j] <= nums[i]){ //从后往前,找到比nums[i]大的第一个数
j--;
}
swap(nums,i,j);//交换
}
reverse(nums,i+1);//对从i+1到最后的所有数从大到小排列
}
private void reverse(int[] nums, int i) {
int start = i, j = nums.length - 1;
while (start < j) {
swap(nums, start, j);
start++;
j--;
}
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
notes
The algorithm is not difficult to write, mainly to make it clear throughout the process
First, find the switching point, when the former is larger than the latter, the former is the exchange point.
Just find the latter than the former in the exchange bigger, and for
All numbers behind the former in ascending order