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

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


题目

字典排序问题。。。自己想估计要想破脑袋了。。。有时间再总结一下吧

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,3 → 1,3,2

3,2,1 → 1,2,3
1,1,5 → 1,5,1

public void nextPermutation(int[] A) {    if(A == null || A.length <= 1) return;    int i = A.length - 2;    while(i >= 0 && A[i] >= A[i + 1]) i--; // Find 1st id i that breaks descending order    if(i >= 0) {                           // If not entirely descending        int j = A.length - 1;              // Start from the end        while(A[j] <= A[i]) j--;           // Find rightmost first larger id j        swap(A, i, j);                     // Switch i and j    }    reverse(A, i + 1, A.length - 1);       // Reverse the descending sequence}public void swap(int[] A, int i, int j) {    int tmp = A[i];    A[i] = A[j];    A[j] = tmp;}public void reverse(int[] A, int i, int j) {    while(i < j) swap(A, i++, j--);}

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

你可能感兴趣的文章
Python文件处理之文件写入方式与写缓存(三)
查看>>
zz MBR,EBR
查看>>
C#面向对象12 集合
查看>>
CF359D:Pair of Numbers(数论)
查看>>
Codeforces Round #562 (Div. 2) B. Pairs
查看>>
仿函数
查看>>
Javascript 视觉 逐帧动画(修正版)
查看>>
大学生很迷茫?给应届毕业生的八点建议。
查看>>
leetcode02大数相加
查看>>
新建Java Spring boot项目
查看>>
[读书笔记]机器学习:实用案例解析(1)
查看>>
[LeetCode] Integer to English Words
查看>>
Python中的装饰器——11
查看>>
thinkphp <eq> <if>标签 condition中可以写PHP的判断逻辑
查看>>
clang: error: linker command failed with exit code 1 (use -v to see invocation)
查看>>
Python ThreadPool简单应用多线程
查看>>
用eclipse导入jar包并使其在一个文件夹下
查看>>
org.hibernate.Session常用方法的作用总结
查看>>
斜率优化
查看>>
js遍历Object所有属性
查看>>