Advertisement
sweet1cris

Untitled

Jan 9th, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.06 KB | None | 0 0
  1. public class Solution {
  2.     /**
  3.      * @param nums: A list of integers
  4.      * @return: A list of integers that's next permuation
  5.      */
  6.     public void swapItem(int[] nums, int i, int j) {
  7.         int temp = nums[i];
  8.         nums[i] = nums[j];
  9.         nums[j] = temp;
  10.     }
  11.     public void swapList(int[] nums, int i, int j) {
  12.         while (i < j) {
  13.             swapItem(nums, i, j);
  14.             i ++; j --;
  15.         }
  16.     }
  17.     public int[] nextPermutation(int[] nums) {
  18.         int len = nums.length;
  19.         if ( len <= 1)
  20.             return nums;
  21.         int i = len - 1;
  22.         while (i > 0 && nums[i] <= nums[i - 1])
  23.             i --;
  24.         swapList(nums, i, len - 1);
  25.         if (i != 0) {
  26.             int j = i;
  27.             while (nums[j] <= nums[i - 1]) j++;
  28.             swapItem(nums, j, i-1);
  29.         }
  30.         return nums;
  31.     }
  32. }
  33.  
  34. // version 2
  35. public class Solution {
  36.     /**
  37.      * @param num: an array of integers
  38.      * @return: return nothing (void), do not return anything, modify num in-place instead
  39.      */
  40.      
  41.     public void reverse(int[] num, int start, int end) {
  42.         for (int i = start, j = end; i < j; i++, j--) {
  43.             int temp = num[i];
  44.             num[i] = num[j];
  45.             num[j] = temp;
  46.         }
  47.     }
  48.    
  49.     public int[] nextPermutation(int[] num) {
  50.         // find the last increase index
  51.         int index = -1;
  52.         for (int i = num.length - 2; i >= 0; i--) {
  53.             if (num[i] < num[i + 1]) {
  54.                 index = i;
  55.                 break;
  56.             }
  57.         }
  58.         if (index == -1) {
  59.             reverse(num, 0, num.length - 1);
  60.             return num;
  61.         }
  62.        
  63.         // find the first bigger one
  64.         int biggerIndex = index + 1;
  65.         for (int i = num.length - 1; i > index; i--) {
  66.             if (num[i] > num[index]) {
  67.                 biggerIndex = i;
  68.                 break;
  69.             }
  70.         }
  71.        
  72.         // swap them to make the permutation bigger
  73.         int temp = num[index];
  74.         num[index] = num[biggerIndex];
  75.         num[biggerIndex] = temp;
  76.        
  77.         // reverse the last part
  78.         reverse(num, index + 1, num.length - 1);
  79.         return num;
  80.     }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement