[leetcode]Next Permutation
来源:互联网 发布:淘宝差评最多省份 编辑:程序博客网 时间:2024/05/11 13:34
思路:从数组的后面往前遍历,当找到一个位置 i 的数字比他的前一个位置i-1数字大之后。再从 i 位置向后找,找到一个刚好比i-1位置的数字大的数字j,交换这二个数字,然后从i位置到数组末尾,把数组翻转一遍就好了。
public class Solution { public void nextPermutation(int[] nums) { int len = nums.length; boolean flag = false; for(int i=len-1; i>=1; i--){ if(nums[i]>nums[i-1]){ int j=i; while(j<len-1){ if(nums[j+1]<=nums[i-1] ){ break; } j++; } if(nums[j]>nums[i-1]){ swap(nums,i-1,j); } reverse(nums,i,len-1); flag = true; break; } } if(!flag){ reverse(nums,0,len-1); } } private void reverse(int[] nums,int i,int j){ while(i<j){ swap(nums,i++,j--); } } private void swap(int[] nums,int a,int b){ int temp=nums[a]; nums[a]=nums[b]; nums[b]=temp; }}
0 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
- Struts2 - 常用的constant总结
- Java多线程之Lock的使用
- android删除系统内置apk(system/app目录下apk)
- android studio使用问题及说明
- 网络知识---http请求几种方式
- [leetcode]Next Permutation
- 将txt文本数据导入到Oracle数据库中去
- 字符串加密
- CF A. Greg and Array (区间离线处理)
- linux 反汇编分析变量地址并用gdb修改运行中的程序内存变量实验
- sql经典题目
- android studio使用问题及说明
- 长方柱类
- android 实现循环播放的文字跑马灯效果