Next Permutation_Leetcode_#31
来源:互联网 发布:python是什么语言 编辑:程序博客网 时间:2024/06/03 22:04
1.题目
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
2 解法
public class Solution { public void nextPermutation(int[] nums) { int size = nums.length; if(size <= 1){ return; } int i = size - 1; for(; i >= 1; i--){ if(nums[i] > nums[i-1]){ break; } } if(i != 0){ swap(nums, i - 1); } reverse(nums, i); } // swap from the end, find the first element that is less than nums[i], sawp it with nums[i] and return; public void swap(int[] nums, int i){ int j = nums.length - 1; for(; j > 0; j--){ if(nums[j] > nums[i]){ int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; return; } } } public void reverse(int[] nums, int i){ int right = nums.length - 1; int left = i; while(left < right){ int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; ++left; --right; } }}
0 0
- Next Permutation_Leetcode_#31
- 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
- 9.8~9.10 训练总结
- JS和jQ的总结--事件
- Android - 比较日期的时间部分
- 上台阶
- 无符号数除以非2的幂(MagicNumber有进位)
- Next Permutation_Leetcode_#31
- Android - 使用Timer+Handler定时跨线程访问UI控件
- 解决liunx进程杀不死的问题
- 基类和派生类指针转换--dynamic_cast
- MapReduce源码解析之InputFormat
- Java基础面试题
- A build only device cannot be used to run this target.
- PAT advanced-1003详解
- 【华为OJ】汽水瓶