March 12, 2019

31. Next Permutation

31. Next Permutation

参考了这个视频

  1. 从最后一个数字开始看,找到前一位比后一位小的数字
  2. 从这个数字开始,找到下一个比它大的数字
  3. 交换,对后面一部分数字排序 Time = O(n), space = O(1)
class Solution {
    public void nextPermutation(int[] nums) {
        int targetIndex = -1;
        for (int i = nums.length - 1; i > 0; i--) {
            if (nums[i] > nums[i - 1]) {
                targetIndex = i - 1;
                break;
            }
        }
        if (targetIndex == -1) {
            Arrays.sort(nums);
            return;
        }

        int nextIndex = -1;
        int val = Integer.MAX_VALUE;
        for (int i = targetIndex + 1; i < nums.length; i++) {
            if (nums[i] > nums[targetIndex] && nums[i] < val) {
                nextIndex = i;
                val = nums[nextIndex];
            }
        }
        swap(nums, targetIndex, nextIndex);       
        Arrays.sort(nums, targetIndex + 1, nums.length);    
    }
    
    private void swap (int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
comments powered by Disqus