程序媛詹妮弗
终身学习

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 and use only constant 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

 

思路:

给定一个排列,按照字典序把下一个排列找出来。

 

Solution1: 

 

 

 

code:

 1 /*
 2 Time: O(n).  We travese the given array
 3 Space: O(1). We only used constant extra space. 
 4 */
 5 
 6 class Solution {
 7        public void nextPermutation(int[] nums) {
 8         // corner case
 9         if (nums == null || nums.length == 0) return;
10 
11         int replace = nums.length - 2; //为何初始化为这个?因为下面要replace 和replace +1 比较
12         while (replace >= 0) {
13             if (nums[replace] < nums[replace + 1]) break;//从右往左扫
14             replace--;
15         }
16         if (replace < 0) {//说明数组总没有出现nums[replace]<nums[replace+1], 则数组为 654321 这种排序
17             Arrays.sort(nums); //返回题干说述的升序排列
18             return;
19         }
20         int lgrIdx = replace + 1;
21         //从nums[replace]往后,开始找剩下数字中,大于且最接近的nums[replace]的值
22         while (lgrIdx < nums.length && nums[lgrIdx] > nums[replace]) {
23             lgrIdx++;
24         }
25         int temp = nums[replace];
26         nums[replace] = nums[lgrIdx - 1];
27         nums[lgrIdx - 1] = temp;
28         Arrays.sort(nums, replace + 1, nums.length);
29     }
30 }

 

posted on 2018-10-18 06:16  程序媛詹妮弗  阅读(145)  评论(0编辑  收藏  举报