LeetCode:Next Permutation
2016-07-01 12:44
405 查看
Next Permutation
Total Accepted: 70533 TotalSubmissions: 261357 Difficulty: Medium
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
Subscribe to see which companies asked this question
Hide Tags
Array
Hide Similar Problems
(M) Permutations (M)
Permutations II (M) Permutation Sequence (M)
Palindrome Permutation II
思路:
下一个排列数,定义:比当前数大的最小数。
1.从左往右找到第一个“顺序”,即nums[i-1] <nums[i],因此nums[i,n-1]都是“逆序”;
2.从定义可知,我们要从[i,n-1]中找一个最小的数与nums[i-1]交往,然后将nums[i,n-1]“顺序”排序即可。
如:nums = [6,2,5,4,3,1], n = 6;
由1)找到i = 2,nums[2,5] = [5,4,3,1]是“逆序”;
由2)交换后得 nums=[6,3,5,4,2,1],再将[i, n-1]顺序,得解[6,3,1,2,4,5];
由于[i, n-1]已是逆序,直接逆序就变成“顺序”,时间O(n),即总时间O(n);
java code:
public class Solution { public void nextPermutation(int[] nums) { int n = nums.length; int i = n-1; // 从左到右,找到第一个“顺序”位置 while(i > 0) { if(nums[i-1] < nums[i]) break; i--; } if(i==0) { reverse(nums, 0, n-1); return; } // 找到第一个大于i位置值的下标j,并与i位置值交换 int j = n-1; int val = nums[i-1]; while(i < j && val >= nums[j]) j--; swap(nums, i-1, j); // 逆序[i,n-1]部分 reverse(nums, i, n-1); } // 自定义函数:逆序 void reverse(int[] nums, int lo, int hi) { while(lo < hi) { swap(nums, lo, hi); lo++;hi--; } } // 交换 void swap(int[] nums, int lo, int hi) { nums[lo] ^= nums[hi]; nums[hi] ^= nums[lo]; nums[lo] ^= nums[hi]; } }
相关文章推荐
- leetcode 100. Same Tree
- [3.0.1]性能调优之调节并行度
- 矩阵分解(rank decomposition)文章代码汇总
- linxu学习之android(一):linux下安装android studio 、android sdk安装教程
- MVC MVP 和 MVVM 的图示
- Android中的坐标系以及获取坐标的方法
- 获取用户SID
- NSNotification调用机制
- python -正则表达式
- 土地购买[Usaco2008 Mar][bzoj 1597]
- js如何判断IE浏览器的版本包括IE11
- java中for和foreach的区别
- JAVA基础知识篇
- Android白话启动篇(Android booting process)
- python判断字符串编码的简单实现方法(使用chardet)
- 服务器TIME_WAIT和CLOSE_WAIT详解和解决办法
- Codeforces-687B Remainders Game
- solr6定时增量更新
- 从MVC到前后端分离
- 利用OpenCV的findContours作轮廓检测