LeetCode 31 - Next Permutation
2016-02-25 17:10
344 查看
Next Permutation
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
My Code
class Solution { public: void nextPermutation(vector<int>& nums) { int size = nums.size(); if (size < 1) return; int max = nums.back(); int i = size - 2; for (; i >= 0; i--) { if (nums[i] < max) { int greater = max + 1; int idx = -1; for (int j = i + 1; j < size; j++) if (nums[j] > nums[i] && nums[j] < greater) { greater = nums[j]; idx = j; } nums[idx] = nums[i]; nums[i] = greater; sort(nums.begin()+i+1, nums.end()); break; } else max = nums[i]; } if (i == -1) sort(nums.begin(), nums.end()); } };Runtime: 12 ms
相关文章推荐
- 思考即学习,因为创造,所以热爱!
- 几分钟内学习 Clojure
- 零基础如何系统地学习前端开发
- windows Azure平台开发
- mysql 表分区技术
- C#中的委托和事件
- java工具
- javaWeb提高并发数之二十三条
- android4.x 耳机插拔检测机制
- UI控件学习
- InJavaWeTrust
- ios layout机制相关方法
- C++ explicit关键字
- 12 个非常实用的 jQuery 代码片段
- 关于调用strcpy()函数时总是报错问题,5种方法解决!
- 第十六周 程序阅读
- 使用EditText+ListView并结合TextWatcher实现输入关键字筛选数据
- GCD Again
- 图书管理系统 C语言
- 【PA2011】【BZOJ3073】Journeys