題目鏈接
31.下一個排列
class Solution {public void nextPermutation(int[] nums) {//1.從右往左找第一個非逆序的數aint left = nums.length - 2; //這里是為了找不到順序對的時候正好停在-1while (left >= 0 && nums[left] >= nums[left + 1]) { //一定要取等號,因為相等要繼續尋找left--;}//2.從右往左找到第一個大于a的數bif (left >= 0) {int right = nums.length - 1;while (right > left && nums[right] <= nums[left]) { //取等號right--;}//3.交換a,bswap(nums, left, right);}//4.將a后面的數逆序reverse(nums, left + 1);}public void swap(int[] nums, int a, int b) {int temp = nums[a];nums[a] = nums[b];nums[b] = temp;}public void reverse(int[] nums, int begin) {int end = nums.length - 1;while (begin < end) {swap(nums, begin, end);begin++;end--;}}
}
小結:如果在步驟 1 找不到順序對,說明當前序列已經是一個降序序列,即最大的序列,我們直接跳過步驟 2、3 執行步驟 4,即可得到最小的升序序列。