LeetCode -- Next Permutation
来源:互联网 发布:日本文化史知乎 编辑:程序博客网 时间:2024/05/29 15:32
题目描述:
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--; } }}
1 0
- LeetCode: Next Permutation
- LeetCode Next Permutation
- LeetCode : Next Permutation
- [Leetcode] Next Permutation
- [LeetCode] Next Permutation
- [Leetcode] Next Permutation
- leetcode 88: Next Permutation
- [LeetCode]Next Permutation
- LeetCode-Next Permutation
- [leetcode]Next Permutation
- LeetCode - Next Permutation
- LeetCode 31: Next Permutation
- 【leetcode】Next Permutation
- LeetCode题解:Next Permutation
- 【LeetCode】Next Permutation
- [LeetCode] Next Permutation
- LeetCode Next Permutation
- leetCode | Next Permutation
- Android 一个ListView添加多个Adapter
- HTTP Request GET, HEAD, POST, PUT, DELETE, OPTIONS, TRACE Methods
- 【计蒜客】基础算法入门之快速排序
- ArcGIS10.1桌面怎么使用ArcSDE服务连接
- jquery.cookie.js的见解
- LeetCode -- Next Permutation
- [error handle][java web]Cannot call sendRedirect() after the response has been committed
- “The Android NDK cannot be installed into a path with spaces”的解决方法
- Piwik网站分析软件学习
- 【UCOSII】任务管理原理
- 数据库表结构导出到word文档常用工具
- java 线程学习--2
- thinkphp的目录常量在入口文件index.php里定义
- ZTree+Struts2+ajax+json实现checkbox权限树