博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
31. Next Permutation
阅读量:5234 次
发布时间:2019-06-14

本文共 2005 字,大约阅读时间需要 6 分钟。

Problem statement:

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:

  • loop from the back of the array.
  • record the maximum of all traversec elements.
  • if current element is less than the maximum value
  • find the element which is just greater than it from it`s back.
  • swap these two elements and breaks
  • if we did not do any swap, that means current element is already the maximum value for current nums. the return value is the reverse result
class Solution {public:    void nextPermutation(vector
& nums) { if(nums.size() <= 1){ return; } int size = nums.size(); int max_val = nums[nums.size() - 1]; bool find = false; for(int ix = nums.size() - 2; ix >= 0; ix--){ if(max_val > nums[ix]){ sort(nums.begin() + ix + 1, nums.end()); for(int i = ix + 1; i < size; i++){ // find the element just greater than nums[ix] if(nums[i] > nums[ix]){ // swap these two elements swap(nums[i], nums[ix]); find = true; // find the final solution and exit break; } } break; } else { max_val = nums[ix]; } } // if current arrange is already the maximum value // reverse it to the mimimum value if(!find){ reverse(nums.begin(), nums.end()); } return; }};

转载于:https://www.cnblogs.com/wdw828/p/6828761.html

你可能感兴趣的文章
Eclipse配置 自动补全功能 快捷键 alt+/
查看>>
抖动效果
查看>>
DataContract和DataMember的作用
查看>>
来自XP的道别信
查看>>
CRM系统的两个核心
查看>>
js如何获取response header信息
查看>>
python_文件的打开和关闭
查看>>
mysql archive存储引擎导入数据报duplicate key
查看>>
ADO.NET介绍
查看>>
iOS: 数据持久化方案
查看>>
Neo4j学习笔记
查看>>
【C#】【Thread】Monitor和Lock
查看>>
builder模式的新学习
查看>>
UVALive - 3635 - Pie(二分)
查看>>
生活中的五个球
查看>>
非静态内部类不能拥有静态变量 为什么
查看>>
android.os.NetworkOnMainthreadexception处理
查看>>
数据库复习⑥
查看>>
jQuery的中文乱码问题[转]
查看>>
bzoj 2005 & 洛谷 P1447 [ Noi 2010 ] 能量采集 —— 容斥 / 莫比乌斯反演
查看>>