標籤:
題目:
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--; } } }
[LeetCode-JAVA] Next Permutation