LeetCode 31: Next Permutation

发布时间:2017-6-26 11:28:08 编辑: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用户账号管理

相关文章

相关评论

本站评论功能暂时取消,后续此功能例行通知。

一、不得利用本站危害国家安全、泄露国家秘密,不得侵犯国家社会集体的和公民的合法权益,不得利用本站制作、复制和传播不法有害信息!

二、互相尊重,对自己的言论和行为负责。