Java for LeetCode 031 Next Permutation
Next Permutation
Total Accepted: 33595 Total Submissions: 134095
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.
解题思路:
题目不难,关键是理解题目的意思: 如果把nums看做一个数字的话,即返回比原来数大的最小的数(如果没有(原数是降序排列)则返回升序排列)。
也就是字典排序,JAVA实现如下:
static public void nextPermutation(int[] nums) { int index = nums.length - 1; while (index >= 1) { if (nums[index] > nums[index - 1]) { int swapNum=nums[index-1],swapIndex = index+1; while (swapIndex <= nums.length - 1&& swapNum < nums[swapIndex]) swapIndex++; nums[index-1]=nums[swapIndex-1]; nums[swapIndex-1]=swapNum; reverse(nums,index); return; } index--; } reverse(nums,0); } static void reverse(int[] nums,int swapIndex){ int[] swap=new int[nums.length-swapIndex]; for(int i=0;i<swap.length;i++) swap[i]=nums[nums.length-1-i]; for(int i=0;i<swap.length;i++) nums[swapIndex+i]=swap[i]; }