LeetCode刷题实战31:下一个排列
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做下一个排列,我们先来看题面:
https://leetcode-cn.com/problems/next-permutation/
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place and use only constant extra memory.
题意
样例
一些例子,输入位于左侧列,其相应输出位于右侧列。
1,2,3
→1,3,2
3,2,1
→1,2,3
1,1,5
→1,5,1
题解
public class Solution {
public void nextPermutation(int[] nums) {
int n = nums.length;
int i = n - 1;
for(; i >= 1; i--) {
if(nums[i] > nums[i - 1]) {
break;
}
}
if(i >= 1) {
int j = n - 1;
for(; j >= i; j--) {
if(nums[j] > nums[i - 1]) {
break;
}
}
swap(i - 1, j, nums);
reverse(nums, i);
}else {
reverse(nums, 0);
}
}
private void reverse(int[] nums, int index) {
int i = index;
int j = nums.length - 1;
while(i < j) {
swap(i, j, nums);
i++;
j--;
}
}
private void swap(int i, int j, int[] nums) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
上期推文: