zoukankan      html  css  js  c++  java
  • LeetCode

    题目:

    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, do not allocate 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,31,3,2
    3,2,11,2,3
    1,1,51,5,1

    思路:

    摘自Stack Overflow:

    Find the highest index i such that s{i} < s{i+1}. If no such index exists, the permutation is the last permutation. Find the highest index j > i such that s{j} > s{i}. Such a j must exist, since i+1 is such an index. Swap s{i} with s{j}. Reverse all the order of all of the elements* after index i.

    package string;
    
    public class NextPermutation {
    
        public void nextPermutation(int[] nums) {
            int len;
            if (nums == null || (len = nums.length) < 2) return;
            int index1 = -1;
            for (int i = 0; i < len - 1; ++i) {
                if (nums[i + 1] > nums[i])
                    index1 = i;
            }
            
            if (index1 != -1) {
                int index2 = index1 + 1;
                for (int j = index2 + 1; j < len; ++j) {
                    if (nums[j] > nums[index1])
                        index2 = j;
                }
                
                swap(nums, index1, index2);
                reverse(nums, index1 + 1, len);
            } else {
                reverse(nums, 0, len);
            }
        }
        
        private void swap(int[] nums, int i, int j) {
            int tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }
        
        private void reverse(int[] nums, int start, int end) {
            for (int i = start; i < (end - start) / 2 + start; ++i) {
                swap(nums, i, end - i + start - 1);
            }
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            NextPermutation n = new NextPermutation();
            int[] nums = { 1,3,2 };
            n.nextPermutation(nums);
            for (int i = 0; i < nums.length; ++i)
                System.out.println(nums[i]);
        }
    
    }
  • 相关阅读:
    easyui datagride 两种查询方式
    SharePoint常用目录介绍
    sharepoint 2013 入门1_ 建立一个网页程序
    Windows2012 显示我的电脑
    你知道 react-color 的实现原理吗
    如何实现 Promise 池
    如何使 pdf 文件在浏览器里面直接下载而不是打开
    macOS 安装 oh-my-zsh 之后 node 失效的问题
    剑指offer[47]——求1+2+3+...+n
    剑指offer[46]——孩子们的游戏(圆圈中最后剩下的数)
  • 原文地址:https://www.cnblogs.com/null00/p/5066680.html
Copyright © 2011-2022 走看看