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).spa

The replacement must be in-place, do not allocate extra memory.code

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,1blog

 

 
 本題開始的時候題意沒有讀懂,看了別人的解釋纔看懂,大體思路是
1.從右面往左面遍歷,若是找到數組下一個的值小於(不包括等於)當前值(即原本是從右往左是遞增序列,可是被打斷的元素)提取出來
2.再一次從右往左遍歷,直到當前數組值大於提取出來的值後,交換這兩個位置。
3.將從右到左不斷遞增的數組區間反轉。
代碼以下:
 1 public class Solution {
 2     public void nextPermutation(int[] nums) {
 3         int index = nums.length;
 4         for(int i=nums.length-1;i>=1;i--){
 5             if(nums[i-1]>=nums[i]) continue;
 6             index = i-1;
 7             break;
 8         }
 9         if(index!=nums.length){
10             for(int i=nums.length-1;i>=index;i--){
11             if(nums[i]<=nums[index]) continue;
12             swap(nums,index,i);
13             break;
14             }
15             reverse(nums,index+1,nums.length-1);
16         }else{
17             reverse(nums,0,nums.length-1);
18         }
19     }
20     public void swap(int[] nums,int i,int j){
21         int temp = nums[i];
22         nums[i] = nums[j];
23         nums[j] = temp;
24     }
25     public void reverse(int[] nums,int left,int right){
26         while(left<right){
27             swap(nums,left++,right--);
28         }
29     }
30 }

本題主要考查細心程度。it

相關文章
相關標籤/搜索