博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Leetcode] Next Permutation
阅读量:5085 次
发布时间:2019-06-13

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

1. From the last index, we seach the first decrease order, such i,i+1 and num[i]<num[i+1]

2. From the last index to i+1, we search the first element which is larger than num[i], such as k, swap(i,k)

3. Swap the element from i+1 to the last one, namely to sort them to increase order(left to right viewpoint)

Take an example.

13542

The first decrease order is 35

then search the first element from right to left which is larger than 3, get 4, swap 3 and 4

13542 -> 14532 -> 14235

The last step is to change the order from 5 to 2 to be increase order.

1 /* 2 Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.  3  4 If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).  5  6 The replacement must be in-place, do not allocate extra memory.  7  8 Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 9 1,2,3 → 1,3,210 3,2,1 → 1,2,311 1,1,5 → 1,5,112 13 */14 15 public class Solution {16     public void nextPermutation(int[] nums) {17         //search for the first decrease order,from right to left-hand18         int i=nums.length-1;19         for(;i>0;i--){20             if(nums[i]>nums[i-1]){21                 break;22             }23         }24         //if there is no decrease order, just return the increase order25         if(i==0){26             Arrays.sort(nums);27             return;28         }29         i--;30         int j=nums.length-1;31         for(;j>=0;j--){32             if(nums[j]>nums[i]){
//get it here33 int tmp = nums[j];34 nums[j]=nums[i];35 nums[i]=tmp;36 break;37 }38 }39 //swap40 int begin=i+1;41 int end=nums.length-1;42 while(begin

 

转载于:https://www.cnblogs.com/deepblueme/p/4724871.html

你可能感兴趣的文章
SQL Server 使用作业设置定时任务之一(转载)
查看>>
第二阶段冲刺-01
查看>>
BZOJ1045 HAOI2008 糖果传递
查看>>
JavaScript 克隆数组
查看>>
eggs
查看>>
python3 生成器与迭代器
查看>>
java编写提升性能的代码
查看>>
list 容器 排序函数.xml
查看>>
《Genesis-3D开源游戏引擎完整实例教程-跑酷游戏篇03:暂停游戏》
查看>>
CPU,寄存器,一缓二缓.... RAM ROM 外部存储器等简介
查看>>
git .gitignore 文件不起作用
查看>>
Alan Turing的纪录片观后感
查看>>
c#自定义控件中的事件处理
查看>>
IOS--沙盒机制
查看>>
使用 JointCode.Shuttle 访问任意 AppDomain 的服务
查看>>
sqlite的坑
查看>>
digitalocean --- How To Install Apache Tomcat 8 on Ubuntu 16.04
查看>>
【题解】[P4178 Tree]
查看>>
Mongo自动备份
查看>>
cer证书签名验证
查看>>