博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
31. Next Permutation
阅读量:6583 次
发布时间:2019-06-24

本文共 1568 字,大约阅读时间需要 5 分钟。

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,23,2,1 → 1,2,31,1,5 → 1,5,1

难度:medium

题目:

实现下一个排列数,将数字按词法顺序重新排列为下一个更大的数字置换。如果这样的排序不存在,它一定轮转到了最小的那个数。
必须原地置换并且只允许使用常量空间。

思路:参照C++ STL库中实现的next_permutation

Runtime: 8 ms, faster than 98.59% of Java online submissions for Next Permutation.

Memory Usage: 31.2 MB, less than 0.97% of Java online submissions for Next Permutation.

class Solution {    /**    * 1. find i <  j (i + 1) from end to start    * 2. find i < k swap (i, k) from end to start    * 3. reverse [j, last]    */    public void nextPermutation(int[] nums) {        if (null == nums || nums.length <= 1) {            return;        }                int right = nums.length - 1;        int j = right;        for (; j > 0; j--){            if (nums[j - 1] < nums[j]) break;        }        for (int k = right; k >= 0; k--) {            if (j > 0 && nums[k] > nums[j - 1]) {                swapArray(nums, j - 1, k);                break;            }        }        for (; j < right; j++, right--) {            swapArray(nums, j, right);        }    }        private void swapArray(int[] a, int i, int j) {        int t = a[i];        a[i] = a[j];        a[j] = t;    }}

转载地址:http://nnino.baihongyu.com/

你可能感兴趣的文章
项目、软件开发过程中版本术语
查看>>
T-SQL中INSERT、UPDATE
查看>>
openSUSE13.2安装ruby和rails
查看>>
python 高级函数
查看>>
F.Cards with Numbers
查看>>
简单入门Buffer
查看>>
OO第四阶段总结
查看>>
javascript总结02
查看>>
创建windows服务
查看>>
用main函数传参做简单的计算器的代码
查看>>
python中struct.unpack的用法
查看>>
体绘制(Volume Rendering)概述之4:光线投射算法(Ray Casting)实现流程和代码(基于CPU的实现)...
查看>>
Python实践之(七)逻辑回归(Logistic Regression)
查看>>
PAT (Advanced Level) 1107. Social Clusters (30)
查看>>
【开源社群系统研发日记五】ThinkSNS+ 是如何计算字符显示长度的
查看>>
Nodejs日志管理log4js
查看>>
python获取昨日日期
查看>>
海康威视 - 萤石云开放平台 js 版
查看>>
关于分销平台
查看>>
jquery实用的一些方法
查看>>