1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
public class NextPermutation { public void nextPermutation(int[] nums) { if (nums == null || nums.length < 2) { return; } int length = nums.length - 1; while (length > 0 && nums[length - 1] >= nums[length]) { length--; } if (length == 0) { Arrays.sort(nums); return; } if (length == nums.length - 1) { int tmp = nums[length]; nums[length] = nums[length - 1]; nums[length - 1] = tmp; return; } int target = length + 1; while (target < nums.length && nums[target] > nums[length - 1]) { target++; } target--; int tmp = nums[length - 1]; nums[length - 1] = nums[target]; nums[target] = tmp; Arrays.sort(nums, length, nums.length); } }
|