image.png

解决思路

  1. class Solution {
  2. public void nextPermutation(int[] nums) {
  3. if (nums == null || nums.length == 0) return;
  4. int firstIndex = -1;
  5. for (int i = nums.length - 2; i >= 0; i--) {
  6. if (nums[i] < nums[i + 1]) {
  7. firstIndex = i;
  8. break;
  9. }
  10. }
  11. if (firstIndex == -1) {
  12. reverse(nums, 0, nums.length - 1);
  13. return;
  14. }
  15. int secondIndex = -1;
  16. for (int i = nums.length - 1; i >= 0; i--) {
  17. if (nums[i] > nums[firstIndex]) {
  18. secondIndex = i;
  19. break;
  20. }
  21. }
  22. swap(nums, firstIndex, secondIndex);
  23. reverse(nums, firstIndex + 1, nums.length - 1);
  24. return;
  25. }
  26. private void reverse(int[] nums, int i, int j) {
  27. while (i < j) {
  28. swap(nums, i++, j--);
  29. }
  30. }
  31. private void swap(int[] nums, int i, int i1) {
  32. int tmp = nums[i];
  33. nums[i] = nums[i1];
  34. nums[i1] = tmp;
  35. }
  36. }