Leetcode Next Permutation

本文介绍了一个高效的算法来解决LeetCode中的下一个排列问题。通过从数组末尾向前查找第一个不满足降序排列的元素,并与后续子数组中大于该元素的最小值交换,再将剩余子数组反转以得到下一个最大的排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Leetcode Next Permutation ,通过查看排列的特性,可以发现,每一次改变值的位置之后的元素都是按升序排列的,如:arr = [5, 4, 2, 3, 1],可以知道其下一个排列为:brr = [5, 4, 3, 1, 2],对于arr可以发现元素“2”后面元素为降序排列,那么如果要生成下一个序列,就应该在2之后找出一个大于2的元素代替“2”,可以找到的是3。这样,在“3”出现在“2”的位置后,“3”之后的元素应该进行“归零”,也就是需要进行升序排列。以上就是本算法的基本思想,以下给出cpp代码,以及相关测试如下:

#include<iostream>
#include<vector>

using namespace std;
// In array arr, if there is i < j, and arr[i] < arr[j], we can conclued that
// there is next permutation for arr.
// So we search from the end to front, and check that there is
// arr[i] > arr[i - 1]. If we get such i, we just swap arr[i - 1] with the
// first element in arr[i:end] which greater than arr[i - 1]. Otherwise we
// just reverse the arr as ther requirement of the question.
class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int len = nums.size() - 1;
        int pos = len;
        int temp;
        // Find the ajancent reverse element.
        while (pos > 0 && nums[pos] <= nums[pos - 1]) {
            pos --;
        }
        // If we find it, just swap it with the first element greater than it
        // by searching from end to begin.
        if (pos > 0) {
            temp = nums[pos - 1];
            int swap_pos = len;
            for (; swap_pos >= pos; swap_pos --) {
               if (nums[swap_pos] > nums[pos - 1]) {
                   break;
               }
            }
            nums[pos - 1] = nums[swap_pos];
            nums[swap_pos] = temp;
        }
        // Reverse the left element in ascend order.
        for (int i = 0; i < (len - pos + 1) / 2; i ++) {
            temp = nums[pos + i];
            nums[pos + i] = nums[len - i];
            nums[len - i] = temp;
        }
    }
};
int main(int argc, char* argv[]) {
    Solution so;
    vector<int> test;
    test.push_back(1);
    test.push_back(3);
    test.push_back(2);
    so.nextPermutation(test);
    for (int i = 0; i < test.size(); i ++) {
        cout<<test[i]<<" ";
    }
    cout<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值