leetcode-cn Daily Challenge on November 10th, 2020.
leetcode Daily Challenge on January 31th, 2021.
Difficulty : Medium
Related Topics : Array
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
- mine
- Java
Runtime: 0 ms, faster than 100.00%, Memory Usage: 39.4 MB, less than 50.00% of Java online submissions
// O(N)time // O(1)space public void nextPermutation(int[] nums) { int len = nums.length; if (len < 2) { return; } int index = len - 1; while (index > 0 && nums[index - 1] >= nums[index]) { index--; } if (index != 0) { int val = nums[index - 1]; int j = len - 1; //find the last i which make nums[i] > val while (j >= index) { if (nums[j] > val) break; j--; } int t = nums[j]; nums[j] = nums[index - 1]; nums[index - 1] = t; } int s = index, e = len - 1; while (s < e) { int t = nums[s]; nums[s] = nums[e]; nums[e] = t; s++; e--; } }
- Java
- the most votes
Runtime: 0 ms, faster than 100.00%, Memory Usage: 39.4 MB, less than 50.00% of Java online submissions
public void nextPermutation(int[] num) { int n=num.length; if(n<2) return; int index=n-1; while(index>0){ if(num[index-1]<num[index]) break; index--; } if(index==0){ reverseSort(num,0,n-1); return; } else{ int val=num[index-1]; int j=n-1; while(j>=index){ if(num[j]>val) break; j--; } swap(num,j,index-1); reverseSort(num,index,n-1); return; } } public void swap(int[] num, int i, int j){ int temp=0; temp=num[i]; num[i]=num[j]; num[j]=temp; } public void reverseSort(int[] num, int start, int end){ if(start>end) return; for(int i=start;i<=(end+start)/2;i++) swap(num,i,start+end-i); }