LeetCode -- Next Permutation
2015-09-22 09:51
323 查看
题目描述:
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
给定一个序列,找到下一个排序。
思路:
将index, index2 = -1;
1. 从右向左找,如果不满足 num[i+1] < num [i],index = i;
2. 再从右向左找到第一个num[i] > num[index] 的数,index 2 = i;
3. 交换num[index]和num[index2]
4. 将num[index+1... n] 的数逆置。
实现代码:
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
给定一个序列,找到下一个排序。
思路:
将index, index2 = -1;
1. 从右向左找,如果不满足 num[i+1] < num [i],index = i;
2. 再从右向左找到第一个num[i] > num[index] 的数,index 2 = i;
3. 交换num[index]和num[index2]
4. 将num[index+1... n] 的数逆置。
实现代码:
public class Solution { public void NextPermutation(int[] nums) { var index = -1; for(var i = nums.Length - 1; i > 0; i--){ if(nums[i] > nums[i-1]){ index = i-1; break; } } var index2 = -1; if(index != -1){ for(var i = nums.Length - 1; i >= 0; i--){ if(nums[i] > nums[index]){ index2 = i; break; } } } if(index != -1 && index2 != -1){ var t = nums[index]; nums[index] = nums[index2]; nums[index2] = t; } var k = index + 1; var j = nums.Length - 1; while(k < j){ var tmp = nums[k]; nums[k] = nums[j]; nums[j] = tmp; k++; j--; } } }
相关文章推荐
- eclipse配置编码环境为utf-8和设置字体
- HTTP Request GET, HEAD, POST, PUT, DELETE, OPTIONS, TRACE Methods
- linux(nginx)
- ios多手势同时进行
- caffe安装系列——安装GCC4.7和G++4.7并降级
- 【计蒜客】基础算法入门之快速排序
- [error handle][java web]Cannot call sendRedirect() after the response has been committed
- QTP设置变量和输出显示
- 远程访问linux环境安装图形界面问题解决汇总
- MySQL多实例配置(两)
- LeetCode -- Course Schedule II
- Command /usr/bin/codesign failed with exit code 1
- 【视频信号】为何视频信号种类如此的多?
- URAL 1009 K-based Numbers (DFS)
- ffmpeg/x264支持场编
- CoreData 概述
- Xcode7.0提交二进制文件到AppStore时遇到 ITMS-90535 错误
- 雅虎前端优化法则
- C基础--函数的回调
- 【Soot学习记录1】新Class文件的生成及错误处理