31. 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 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

 

 1 class Solution {
 2     public int find(int []nums, int v, int l1, int r1) {
 3         for (int i = l1; i <= r1; ++i) {
 4             if (nums[i] > v) return i;
 5         }
 6         return 0;
 7     }
 8     public void nextPermutation(int[] nums) {
 9         int n = nums.length;
10         
11         int i = n - 1;
12         
13        
14         while (i - 1 >= 0 && nums[i] <= nums[i - 1]){
15             i--;
16         }
17           
18         
19         if (i == 0) {
20             Arrays.sort(nums);
21         } else {
22             Arrays.sort(nums, i, n);
23             int id = find(nums, nums[i - 1], i, n - 1);
24             int temp = nums[id];
25             nums[id] = nums[i - 1];
26             nums[i - 1] = temp;
27         }
28         
29         
30     }
31 }

 

posted @ 2020-02-14 18:34  hyx1  阅读(96)  评论(0编辑  收藏  举报