標籤: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
題意:
開始就沒讀懂題,後來終於找到一個說明白的解釋。
* 首先要明白:什麼是next permutation. 簡單點說,如果輸入的數字有大小的話,那麼 next permutation就是下一個大於它並"最接近"它的全排列.
* 比如123, 下一個使用 這三個數位排列就是132(213, 312雖然也是全排列,但是都比132大)
* 如果這個全排列已經是最大的了(全部升序排列),那麼它的next permutation就來一個 "頭尾想接"(就是最小的數字):
* 比如321的排列已經是最大的了, 所以next permutation 就是把321完全反轉成最小的123
演算法分析:
參考:http://harrifeng.github.io/algo/leetcode/next-permutation.html
實現一般分下面四個步驟(對應圖):
- 從後往前找,找到第一個array[i] < array[i+1]的地方, 這個地方是整個字串 最晚的"升序"的地方,而且在數字尾端,更改的話最容易做到"最接近".通過從後往前 逐個比較,我們發現8這個數字是一個分界線.8後面的數字都是降序的(也就是最大的了)
- 我們如果直接把6和8一交換,肯定也會產生一個permutation,但是不是"最接近的",怎樣 找到"最接近"的呢,就要從1到8後面這端尋找一個比6大,並且和6差距最小的(也就是從 後往前第一個比6大的數字),我們找到了是7
- 7作為最佳選擇,和6進行調換. 7後面肯定還是decrease的狀態(也就是能組成的最大值)
- 為了達到"最接近",我們在6變成7的情況下已經增長很多了.所以我們要把7後面的一系列 decrease的數組反轉(也就是能組成的最小值)
AC代碼:
<span style="font-size:12px;">public class Solution { public static void nextPermutation(int[] num) { if (num.length <= 1) return; for (int i = num.length - 2; i >= 0; i--) { if (num[i] < num[i+1]) { int j; for (j = num.length - 1; j >= i; j--) { if (num[i] < num[j]) //找到比num[i]大但是和其差距最小的一個 break; } // swap the two numbres int temp = num[i]; num[i] = num[j]; num[j] = temp; // sort the rest of arrays after the swap point Arrays.sort(num, i+1, num.length); return; } } // if the whole array is all in descending order(can't become bigger), // you have to reverse the array for (int i = 0; i < num.length / 2; i++) { int temp = num[i]; num[i] = num[num.length - i - 1]; num[num.length - i - 1] = temp; } return;}}</span>
著作權聲明:本文為博主原創文章,轉載註明出處
[LeetCode][Java] Next Permutation