Share my JAVA solution very easy to understand


  • 0
    W
    public class Solution {
        public void nextPermutation(int[] nums) {
            if (nums == null || nums.length <= 1) return;
            
            int minIndex = -1;
            for (int i = nums.length - 2; i >= 0; i--){
                if (nums[i] < nums[i + 1]){
                    minIndex = i;
                    break;
                }
            }
            if (minIndex == -1){
                Arrays.sort(nums);
                return;
            }
            
            int secondMinIndex = -1;
            for (int i = nums.length - 1; i > minIndex; i--){
                if (nums[i] > nums[minIndex]){
                    secondMinIndex = i;
                    break;
                }
            }
            int tmp = nums[minIndex];
            nums[minIndex] = nums[secondMinIndex];
            nums[secondMinIndex] = tmp;
            Arrays.sort(nums, minIndex + 1, nums.length);
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.