[LeetCode-JAVA] 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, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

题意:找到下一个排列数

思路:主要就是根据经验,要记住这个找排列数的规律

(1) 首先从后往前找到第一个下降的位置,记为i,如果没有则证明是最后一个排序,下一个为原串的逆序

(2) 从i往后,找到比i对应的数值大的当中最小的对应的index(由于后面都是降序的,所以找到第一个小于等于i对应的数值的前一个即为所求),如果没有则为length-1;

注: (例如 2,3,6,5,4,1  第一个降序的为3 比3大的当中 最小的为4)

(3) 交换nums[i] 和 nums[index] 

(4) 将i后面的逆序

代码:

public class Solution {
    public void nextPermutation(int[] nums) {
        if(nums.length < 2)
            return;
        for(int i = nums.length - 2 ; i >= 0 ; i--) {
            if(nums[i] < nums[i+1]) {
               int index = nums.length - 1;
               for(int j = i + 1 ; j < nums.length ; j++) { // 找到比nums[index]大的当中最小的
                   if(nums[j] <= nums[i]){  //一定要有等号哦
                       index = j - 1;
                       break;
                   }
               }
               int temp = nums[i];
               nums[i] = nums[index];
               nums[index] = temp;
               
               reverse(nums, i+1, nums.length-1);
               return;
            }
        }
        
        reverse(nums, 0, nums.length-1);
        return;
    }
    
    public void reverse(int[] nums, int begin, int end) {
        if(begin == end)
            return;
        
        while(begin < end) {
            int temp = nums[begin];
            nums[begin] = nums[end];
            nums[end] = temp;
            begin++;
            end--;
        }
    } 
}
原文地址:https://www.cnblogs.com/TinyBobo/p/4699549.html