zoukankan      html  css  js  c++  java
  • [LC] 31. Next Permutation

    Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

    If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

    The replacement must be in-place and use only constant 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,2
    3,2,1 → 1,2,3
    1,1,5 → 1,5,1

    class Solution {
        public void nextPermutation(int[] nums) {
            int firstSmall = -1;
            for (int i = nums.length - 2; i >= 0; i--) {
                if (nums[i] < nums[i + 1]) {
                    firstSmall = i;
                    break;
                }
            }
            
            if (firstSmall == -1) {
                reverse(nums, 0, nums.length - 1);
                return;
            }
            
            int firstLarge = -1;
            for (int i = nums.length - 1; i >= 0; i--) {
                if (nums[i] > nums[firstSmall]) {
                    firstLarge = i;
                    break;
                }
            }
            swap(nums, firstSmall, firstLarge);
            reverse(nums, firstSmall + 1, nums.length - 1);
        }
        
        private void reverse(int[] nums, int i, int j) {
            while (i < j) {
                swap(nums, i, j);
                i += 1;
                j -= 1;
            }
        }
        
        private void swap(int[] nums, int i, int j) {
            int tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }
    }
  • 相关阅读:
    VMware安装虚拟机(Ubuntu)
    鼠标拖拽事件
    css层叠样式表
    html--form表单常用操作
    python学习之HTML-table标签
    python之web前端day01
    字符串各种操作,关于字符串的内置函数
    正则中匹配次数的问题
    re模块
    Github网站打不开的问题
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12388961.html
Copyright © 2011-2022 走看看