LeetCode 31. Next Permutation
2016-05-26 21:21
344 查看
Problem:
https://leetcode.com/problems/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.
Thought:
from end to begin, find the first number that have number greater than it after, then swap the number with the minimum greater number, the sort the array after the number.
e.g 2 6 3 4 3 1 find arr[2] = 3, the swap it with arr[3] = 4, sort arr[3] to arr[5]
Code C++:
https://leetcode.com/problems/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
Thought:
from end to begin, find the first number that have number greater than it after, then swap the number with the minimum greater number, the sort the array after the number.
e.g 2 6 3 4 3 1 find arr[2] = 3, the swap it with arr[3] = 4, sort arr[3] to arr[5]
Code C++:
class Solution { public: void nextPermutation(vector<int>& nums) { if (nums.size() <= 1) return; for (int i = nums.size() - 2; i >= 0; i--) { int greater_min = i;//greater_min point to the minimum number greater than nums[i] for (int j = nums.size() - 1; j > i; j--) {//get greater_min if (nums[j] > nums[i]) { if (greater_min == i) { greater_min = j; continue; } greater_min = nums[j] < nums[greater_min] ? j : greater_min; } } if (greater_min != i) { swap(nums[i], nums[greater_min]); sort(nums.begin() + i + 1, nums.end()); return; } } sort(nums.begin(), nums.end()); return; } };
相关文章推荐
- Theano: CNMeM is disabled, CuDNN not available
- Javascript Lazyload图片延迟加载特效,降低HTPP连接次数,提高页面访问时间
- 海量数据处理常见面试题
- Hive 数据倾斜解决方案(调优)
- 《统计陷阱》读后感
- 嵌入式 Linux下编译并使用curl静态库
- maven创建项目命令
- 如何利用maven向本地仓库导入官网没有的jar包
- JDK 动态代理实现原理
- X64操作系统组件Jmail无法正常服务问题
- 学习进度12
- K近邻算法(二)程序
- 51nod 1006
- java static的作用详解(转)
- js近期心得体会
- 字符流FileWriter,FileReader、缓冲区,BufferReader,BufferWriter,IO的简单异常处理
- 查找算法之顺序查找
- HDOJ 5410 CRB and His Birthday
- exit()函数
- Java IO - InputStreamReader&OutputStreamWriter