Leetcode 31. Next Permutation
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not po
1 public class Solution { 2 public void NextPermutation(int[] nums) { 3 if (nums == null || nums.Length <= 1) 4 { 5 return; 6 } 7 8 int i = nums.Length - 2; 9 10 while (i >= 0) 11 { 12 if (nums[i] < nums[i + 1]) 13 { 14 break; 15 } 16 17 i--; 18 } 19 20 if (i >= 0) 21 { 22 int j = nums.Length - 1; 23 while (j >= 0) 24 { 25 if (nums[j] > nums[i]) 26 { 27 var tmp = nums[j]; 28 nums[j] = nums[i]; 29 nums[i] = tmp; 30 break; 31 } 32 33 j--; 34 } 35 } 36 37 Array.Sort(nums, i + 1, nums.Length - i - 1); 38 } 39 }
ssible, 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,23,2,1 → 1,2,31,1,5 → 1,5,1

浙公网安备 33010602011771号