31. Next Permutation

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<int>& 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;
    }
};
复制代码
posted @   蓝色地中海  阅读(125)  评论(0编辑  收藏  举报
编辑推荐:
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
阅读排行:
· 手把手教你在本地部署DeepSeek R1,搭建web-ui ,建议收藏!
· 新年开篇:在本地部署DeepSeek大模型实现联网增强的AI应用
· Janus Pro:DeepSeek 开源革新,多模态 AI 的未来
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(三):用.NET IoT库
· 【非技术】说说2024年我都干了些啥
点击右上角即可分享
微信分享提示