public class Solution { /* * @param nums: A list of integers * @return: A list of integers that's previous permuation */ public List<Integer> previousPermuation(List<Integer> nums) { int cur = nums.size() - 1; for(;cur >=1;cur--){ //Find the inflection point, if the previous number is greater than the current number, the previous number is the inflection point, //Find the largest and smaller number after the inflection point, and exchange it with the inflection point if(nums.get(cur - 1) > nums.get(cur)){ int start = cur; int max = nums.get(start); int index = start; for(;start<nums.size();start++){ if(nums.get(start) > max && nums.get(start) < nums.get(cur - 1)){ max = nums.get(start); index = start; } } int temp = nums.get(cur - 1); nums.set(cur - 1, nums.get(index)); nums.set(index, temp); // Arrange the numbers after the inflection point from largest to smallest sortArray(nums,cur); break; } } System.out.println(cur); if(cur <= 0){ sortArray(nums,0); } return nums; } // Arrange the array from the start position to the smallest void sortArray(List<Integer> nums,int start){ List<Integer> temp = new ArrayList<>(); for(int i=start;i<nums.size();i++){ temp.add(nums.get(i)); } Collections.sort(temp); int index = 0; for(int i=temp.size() - 1;i>=0;i--){ nums.set(start + index, temp.get(i)); index ++; } } }
[LintCode] 51. Previous Permutation
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=325506604&siteId=291194637
Ranking