lintcode-medium-Next Permutation
2016-04-02 06:29
253 查看
---恢复内容开始---
Given a list of integers, which denote a permutation.
Find the next permutation in ascending order.
Notice
The list may contains duplicate integers.
Example
For
For
Given a list of integers, which denote a permutation.
Find the next permutation in ascending order.
Notice
The list may contains duplicate integers.
Example
For
[1,3,2,3], the next permutation is
[1,3,3,2]
For
[4,3,2,1], the next permutation is
[1,2,3,4]
public class Solution { /** * @param nums: an array of integers * @return: return nothing (void), do not return anything, modify nums in-place instead */ public int[] nextPermutation(int[] nums) { // write your code here if(nums == null || nums.length <= 1) return nums; int i = nums.length - 1; while(i > 0 && nums[i - 1] >= nums[i]) i--; if(i == 0){ reverse(nums, 0, nums.length - 1); return nums; } i--; int j = i + 1; while(j < nums.length && nums[j] > nums[i]) j++; j--; swap(nums, i, j); reverse(nums, i + 1, nums.length - 1); return nums; } public void swap(int[] nums, int i, int j){ int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; return; } public void reverse(int[] nums, int start, int end){ while(start < end){ swap(nums, start, end); start++; end--; } return; } }
相关文章推荐
- 12.开发板和原理图和数据手册
- [leetcode] 330. Patching Array 解题报告
- 116. 张程易,编程易(01背包)
- Maven3入门
- 91. Decode Ways
- vc在edit控件中动态插入数据滚动显示
- protobuf的nested message嵌套消息。有时会出现序列话再反序列化后,嵌套消息的指却没有了
- js构建ui的统一异常处理方案(二)
- Linux _pthread 属性的控制
- js构建ui的统一异常处理方案(二)
- Linux_ pthread 线程的取消
- Linux _条件变量
- 一步一步利用django创建博客应用(一)
- 22. Generate Parentheses
- Scala.runtime In Compiler Mirror Not Found 怎么解决
- matlab下利用K-Means进行图像分类
- android cmd
- Android面试准备 第一天 第一例 Handler机制
- 使用MacBook Air的4项基本技巧
- tomcat服务最好部署在一个拥有最小权限的用户下