31. Next Permutation
来源:互联网 发布:sql 唯一 distinct 编辑:程序博客网 时间:2024/06/06 02:34
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
思路:
(1)brute force,复杂度O(n^2),
(2)O(N):从右往左先找到第一个左边(记为i)比右边小的point,然后继续从最右边开始找到第一个比i大的point(记为j),i和j交换后,对从i+1位置开始到最右边的数进行排序(因为已经可以明确后面的这些是排好序的,所以直接swap就好了)
public class Solution { public void nextPermutation(int[] nums) { if(nums.length < 2)return ; int i = nums.length - 1; // find the key exchange point i while(i > 0 && nums[i] <= nums[i-1])i--; i--; // biggest if(i == -1){ reverse(nums, 0, nums.length-1); return; } // from right to left, find the swap point j with i int j = nums.length - 1; while(nums[j] <= nums[i])j--; swap(nums, i, j); reverse(nums, i+1, nums.length-1); }private void swap(int[] nums, int i, int j) {int tmp = nums[i];nums[i] = nums[j];nums[j] = tmp;}private void reverse(int[] nums, int i, int j) {while(i < j) {swap(nums, i, j);i++;j--;}}}
Brute Force:
import java.util.Arrays;public class Solution { public void nextPermutation(int[] nums) { for(int i=nums.length-2; i>=0; i--) { int minBigger = Integer.MAX_VALUE, idx = -1; for(int j=i+1; j<nums.length; j++) { if(nums[j] > nums[i]) { if(nums[j] < minBigger) { minBigger = nums[j]; idx = j; } } } if(minBigger != Integer.MAX_VALUE) { int temp = nums[idx]; nums[idx] = nums[i]; nums[i] = temp; //System.out.println(j+1 + " " + i+1); Arrays.sort(nums, i+1, nums.length); return ; } } //if(f) Arrays.sort(nums); }}
0 0
- [LeetCode]31.Next Permutation
- LeetCode --- 31. Next Permutation
- [Leetcode] 31. Next Permutation
- LeetCode 31.Next Permutation
- 31. Next Permutation
- [leetcode] 31.Next Permutation
- [leetcode] 31. Next Permutation
- *LeetCode 31. Next Permutation
- 31. Next Permutation
- Leetcode 31. Next Permutation
- 31. Next Permutation
- 31. Next Permutation
- 31. Next Permutation
- leetcode 31. Next Permutation
- 31. Next Permutation LeetCode
- 31. Next Permutation
- 31. Next Permutation
- 31. Next Permutation
- StrutsPrepareAndExecuteFilter和FilterDispatcher
- 九度 oj 题目1008:最短路径问题
- 基于spark的svm算法实现
- (转) RocketMQ与Kafka对比(18项差异)
- 记录:apache绑定子目录碰到的问题
- 31. Next Permutation
- html规范
- js内存泄漏常见的四种情况
- mysql优化技巧
- 使用REG注册表文件添加、修改或删除注册表键值和子项介绍
- 从零开始使用Maven(一)创建Maven项目
- 关于java native关键字的理解
- 倒计时 插件
- Maven配置环境变量出现的问题