FTPrep, 31 Next Permutation
来源:互联网 发布:淘宝小当家水浒卡 编辑:程序博客网 时间:2024/06/09 16:39
虽说有permutation,其实和其他有permutation字眼的题 套路不一样。
这其实是个数学题,关键是发现permutation 的排序规律,然后按照这个规律,逆向解题。
思路:1,从后往前,相邻梁元素比较,找到第一个降序的相邻一对。2,从降序往后找到最小的比它大的数(因为后面都是升序的,从右到左的升序)。3,找到后和1中的元素互换;4,最简单的一步,把从i+1的元素 到最后一个元素逆序。
简单说就两步:1,找到两个swap的点;2,逆序两点中左点 右边的所有元素。1中有个向左定位,再向右定位的两个遍历;2中写个逆转的方法。
注意的地方,1中向左遍历时,一定要找到降序的,所以while()条件里要加等号;但是1中向右遍历时,因为是找到(最小的)比之大的数,所以遇到相等的情况是也可以停住,因此while() 条件里不包含=号。
代码如下:
public class Solution { public void nextPermutation(int[] nums) { int len = nums.length; if(len==0 || len==1) return; int i=len-2; while(i>=0 && nums[i]>=nums[i+1]) i--; if(i<0){ reverse(nums, 0, len-1); return; } else{ int j=i+1; while(j<len && nums[i]<nums[j]) j++; int tmp=nums[i]; nums[i]=nums[j-1]; nums[j-1]=tmp; reverse(nums, i+1, len-1); return; } } private void reverse(int[] nums, int start, int end){ while(start<end){ int tmp = nums[start]; nums[start]=nums[end]; nums[end]=tmp; start++; end--; } }}
阅读全文
0 0
- FTPrep, 31 Next Permutation
- LeetCode 31: Next Permutation
- [leetcode 31] Next Permutation
- LeetCode(31) Next Permutation
- LeetCode---(31) Next Permutation
- 31-m-Next Permutation
- leetcode 31 -- Next Permutation
- leetcode 31: Next Permutation
- Leecode#31 Next Permutation
- LeetCode(31) Next Permutation
- LeetCode-31 Next Permutation
- Leetcode#31||Next Permutation
- 31Next Permutation
- 31 Next Permutation
- LeetCode 31: Next Permutation
- [31]Next Permutation
- 31 Next Permutation
- 31、Next Permutation
- 给指定ip回复arp reply报文
- 前端页面把long值转换成时间
- java判断字符是否是汉字
- Android studio编译的时候总是报出build里文件的错误
- app打包安装后第一次启动Home时重复进入启动页的问题
- FTPrep, 31 Next Permutation
- PHP之校验用户输入的时间是否符合要求
- C++容器---Pair
- 大话设计模式-Study-Tips-第四章-代理模式
- jdbc连接数据库使用sid和service_name的区别 ?
- 使用JavaMail发送邮件(带附件)
- 智能排序的实现思路
- 数据结构与算法之二分查找
- hdu 5974 A Simple Math Problem