Leetcode-Next Permutation
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3
→ 1,3,2
3,2,1
→ 1,2,3
1,1,5
→ 1,5,1
1 public class Solution { 2 public void nextPermutation(int[] num) { 3 int len = num.length; 4 if (len==0 || len==1) return; 5 6 List<Integer> list = new LinkedList<Integer>(); 7 int index = len-2; 8 list.add(num[len-1]); 9 while (index>=0 && num[index]>=num[index+1]){ 10 list.add(num[index]); 11 index--; 12 } 13 if (index>=0){ 14 list.add(num[index]); 15 int bar = num[index]; 16 Collections.sort(list); 17 int index2 = 0; 18 while (!(list.get(index2)==bar && list.get(index2+1)!=bar)) index2++; 19 int newVal = list.get(index2+1); 20 num[index] = newVal; 21 list.remove(index2+1); 22 for (int i=0;i<list.size();i++){ 23 index++; 24 num[index]=list.get(i); 25 } 26 } else { 27 Collections.sort(list); 28 for (int i=0;i<list.size();i++) 29 num[i]=list.get(i); 30 } 31 32 return; 33 34 } 35 }
Solution 2:
The solution 1 is O(nlogn) complexity, because we sort the part num[i]...num[len-1]. However, we actually can observe that the part num[i+1]...num[len-1] is actually reversely ordered already. Therefore, all we need to do is find out num[j], and reverse the part num[i]...num[len-1]. The complexity is decreased to O(n).
1 public class Solution { 2 public void nextPermutation(int[] num) { 3 int len = num.length; 4 if (len==0 || len==1) return; 5 6 7 int index = len-2; 8 while (index>=0 && num[index]>=num[index+1]){ 9 index--; 10 } 11 if (index>=0){ 12 int bar = num[index]; 13 int index2 = index+1; 14 while (!(index2+1>=len || (num[index2]>bar && num[index2+1]<=bar))) index2++; 15 num[index]=num[index2]; 16 num[index2] = bar; 17 reverse(num,index+1,len-1); 18 } else { 19 reverse(num,0,len-1); 20 } 21 22 return; 23 } 24 25 public void reverse(int[] num,int start,int end){ 26 while (start<end){ 27 int temp = num[start]; 28 num[start] = num[end]; 29 num[end] = temp; 30 start++; 31 end--; 32 } 33 } 34 }