Given a list of integers, which denote a permutation.
Find the previous permutation in ascending order.
Notice
The list may contains duplicate integers.
Example
For [1,3,2,3]
, the previous permutation is [1,2,3,3]
For [1,2,3,4]
, the previous permutation is [4,3,2,1]
public class Solution { /** * @param nums: A list of integers * @return: A list of integers that‘s previous permuation */ public ArrayList<Integer> previousPermuation(ArrayList<Integer> nums) { // write your code if(nums == null || nums.size() == 0) return nums; int i = nums.size() - 2; for(; i >= 0; i--){ if(nums.get(i) > nums.get(i + 1)) break; } if(i == -1){ reverse(nums, 0, nums.size() - 1); return nums; } int j = i + 1; for(int k = j; k < nums.size(); k++){ if(nums.get(k) < nums.get(i) && nums.get(k) >= nums.get(j)) j = k; } swap(nums, i, j); reverse(nums, i + 1, nums.size() - 1); return nums; } public void swap(ArrayList<Integer> nums, int i, int j){ int temp = nums.get(i); nums.set(i, nums.get(j)); nums.set(j, temp); return; } public void reverse(ArrayList<Integer> nums, int i, int j){ while(i < j){ swap(nums, i, j); i++; j--; } return; } }
时间: 2024-11-07 15:41:48