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, do not allocate 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 //https://segmentfault.com/a/1190000003766260 public class Solution { public void nextPermutation(int[] nums) { if(nums.length <= 1){ return; } int i = nums.length - 2; // æ¾å°ç¬¬ä¸ä¸ªä¸éç¹ï¼æä»¬è¦æè¿ä¸ªä¸éç¹çå¼å¢å ä¸ç¹ç¹ // 对äº511è¿ç§æ åµï¼è¦æåé¢ä¸¤ä¸ª1é½è·³è¿ï¼æä»¥è¦å å«çäº while(i >= 0 && nums[i] >= nums[i + 1]){ i--; } // 妿è¿ä¸ªä¸éç¹è¿å¨æ°ç»å ï¼æä»¬æ¾å°ä¸ä¸ªæ¯å®ç¨å¾®å¤§ä¸ç¹çæ°æ¿æ¢ // 妿å¨ä¹å¤ï¼è¯´ææ´ä¸ªæ°ç»æ¯éåºçï¼æ¯å ¨å±æå¤§äº if(i >= 0){ int j = nums.length - 1; // 对äº151ï¼è¿ç§æ åµï¼è¦ææåé¢é£ä¸ª1è·³è¿ï¼æä»¥è¦å å«çäº while(j > i && nums[j] <= nums[i]){ j--; } swap(nums, i, j); } // å°ä¸éç¹ä¹åçé¨åååºææä¸ä¸ªæå°åºå reverse(nums, i + 1, nums.length - 1); } private void swap(int[] nums, int i, int j){ int tmp = nums[j]; nums[j] = nums[i]; nums[i] = tmp; } private void reverse(int[] nums, int left, int right){ while(left < right){ swap(nums, left, right); left++; right--; } } }