Advertisement
sweet1cris

Untitled

Jan 9th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.84 KB | None | 0 0
  1. import java.util.ArrayList;
  2.  
  3. public class Solution {
  4.     /**
  5.      * @param nums: A list of integers
  6.      * @return: A list of integers that's previous permuation
  7.      */
  8.     public void swapItem(ArrayList<Integer> nums, int i, int j) {
  9.         Integer tmp = nums.get(i);
  10.         nums.set(i, nums.get(j));
  11.         nums.set(j, tmp);
  12.     }
  13.     public void swapList(ArrayList<Integer> nums, int i, int j) {
  14.         while ( i < j) {
  15.             swapItem(nums, i, j);
  16.             i ++; j --;
  17.         }
  18.     }
  19.     public ArrayList<Integer> previousPermuation(ArrayList<Integer> nums) {
  20.         int len = nums.size();
  21.         if ( len <= 1)
  22.             return nums;
  23.         int i = len - 1;
  24.         while ( i > 0 && nums.get(i) >= nums.get(i-1) )
  25.             i --;
  26.         swapList(nums, i, len - 1);    
  27.         if ( i != 0) {
  28.             int j = i;
  29.             while ( nums.get(j) >= nums.get(i-1) ) j++;
  30.             swapItem(nums, j, i-1);
  31.         }
  32.        
  33.         return nums;
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement