Next Permutation
来源:互联网 发布:外星文明不存在 知乎 编辑:程序博客网 时间:2024/05/20 03:07
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 class Solution { public void nextPermutation(int[] num) { if(num.length <= 1) return ; for(int i = num.length - 2; i >= 0; i--) { if(num[i] < num[i+1]) { int j; for(j = num.length - 1; j >= i; j--) if(num[i] < num[j]) break; // swap the two numbers. int tmp=num[i]; num[i]=num[j]; num[j]=tmp; //sort the rest of arrays after the swap point. Arrays.sort(num, i+1, num.length); return ; } } //reverse the arrays. for(int i = 0; i < num.length / 2; i++) { int tmp = num[i]; num[i] = num[num.length - i - 1]; num[num.length - i - 1] = tmp; } return ; }}
0 0
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- 8.编写程序,要求如下: 定义名为VolumeArea的抽象类,在其中定义圆周率的值为3.14159,并定义两个抽象方法volume(double r)和area(double r),它们的返回
- 【Linux学习笔记】通用I/O模型概述
- ashx 使用Session 转载
- HDU 2019 Fighting for HDU(贪心水题)
- apache+php5+sqlite3移植
- Next Permutation
- get set
- 剑指off-判断一棵树是否是平衡二叉树
- 12天学好C语言——记录我的C语言学习之路(Day 8)
- Difference between List and Set in Java Collection
- 通过chipscope抓取不到信号怎么办?
- WSDL样式详解
- Linux监控本机当前状态命令
- struts2文件上传