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,23,2,1 → 1,2,31,1,5 → 1,5,1
Java语言: Next Permutation
01 public void nextPermutation(int[] num) {
02 int i=num.length-1;
03 while(i>0 && num[i-1]>=num[i])
04 {
05 i--;
06 }
07 reverse(num,i,num.length-1);
08 if(i-1>=0)
09 {
10 int large=binarySearchUpper(num,i,num.length-1,num[i-1]);
11 swap(num, i-1,large);
12 }
13 }
14
15 public void swap(int[] num, int i, int j)
16 {
17 int temp=num[i];
18 num[i]=num[j];
19 num[j]=temp;
20 }
21
22 public void reverse(int[]num, int start, int end)
23 {
24 while(start<end)
25 {
26 swap(num, start, end);
27 start++;
28 end--;
29 }
30 }
31
32 public int binarySearchUpper(int []num, int lo, int hi, int target)
33 {
34 int mid=(lo+hi)/2;
35 while(lo<hi)
36 {
37 if(num[mid]<=target)
38 {
39 lo=mid+1;
40 }
41 else
42 {
43 hi=mid;
44 }
45 mid=(lo+hi)/2;
46 }
47 return mid;
48 }
02 int i=num.length-1;
03 while(i>0 && num[i-1]>=num[i])
04 {
05 i--;
06 }
07 reverse(num,i,num.length-1);
08 if(i-1>=0)
09 {
10 int large=binarySearchUpper(num,i,num.length-1,num[i-1]);
11 swap(num, i-1,large);
12 }
13 }
14
15 public void swap(int[] num, int i, int j)
16 {
17 int temp=num[i];
18 num[i]=num[j];
19 num[j]=temp;
20 }
21
22 public void reverse(int[]num, int start, int end)
23 {
24 while(start<end)
25 {
26 swap(num, start, end);
27 start++;
28 end--;
29 }
30 }
31
32 public int binarySearchUpper(int []num, int lo, int hi, int target)
33 {
34 int mid=(lo+hi)/2;
35 while(lo<hi)
36 {
37 if(num[mid]<=target)
38 {
39 lo=mid+1;
40 }
41 else
42 {
43 hi=mid;
44 }
45 mid=(lo+hi)/2;
46 }
47 return mid;
48 }
没有评论:
发表评论