LeetCode 31: Next Permutation

发布时间:2016-12-8 19:50:58 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"LeetCode 31: Next Permutation",主要涉及到LeetCode 31: Next Permutation方面的内容,对于LeetCode 31: Next Permutation感兴趣的同学可以参考一下。

Difficulty: 5 Frequency: 2 Problem: 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 Solution: class Solution { public: void nextPermutation(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function if (num.size()<=1) return; int i_sign = -1; for (int i = 1; i<num.size(); i++) { if (num[i]>num[i-1]) i_sign = i; } int i_temp = 0; if (i_sign==-1) { for (int i = 0; i<num.size()-i-1; i++) { i_temp = num[i]; num[i] = num[num.size()-i-1]; num[num.size()-i-1] = i_temp; } return; } int i_smallest_big = i_sign; for (int i = i_sign + 1; i<num.size(); i++) { if (num[i]>num[i_sign-1]) i_smallest_big = num[i]<=num[i_smallest_big]?i:i_smallest_big; } i_temp = num[i_sign-1]; num[i_sign-1] = num[i_smallest_big]; num[i_smallest_big] = i_temp; for (int i = 0; i<num.size()-i-1-i_sign; i++) { i_temp = num[i_sign+i]; num[i_sign+i] = num[num.size()-i-1]; num[num.size()-i-1] = i_temp; } } }; Notes: In line 30, there is one important subtlety. It should be <= NOT <. <= can handle the situation where duplicated numbers occur.

上一篇:基于TCP网络通讯上,自定义协议收发数据
下一篇:Linux学习笔记之 7 Linux用户账号管理

相关文章

相关评论