c++ 显示下一个排列

5us2dqdw  于 2023-04-01  发布在  其他
关注(0)|答案(1)|浏览(81)

我给出了一个整数数组,我必须找到它的整数的下一个字典排列更大的排列。
我正在尝试执行以下代码

class Solution {
public:
    void nextPermutation(vector<int>& nums) {

        int n = nums.size() , i , l;
        for(int i = n-2 ; i >= 0 ; i--){
            if(nums[i] < nums[i+1])
            break;
        }
        if(i<0) {
            reverse(nums.begin() , nums.end());
        }
        else{
            for(int l = n-1 ; l > i ; l--){
                if(nums[l]>nums[i])
                break;
            }
            swap(nums[i], nums[l]);
            reverse(nums.begin() + i + 1 , nums.end());
        }
        }
    };

这里我面临的问题是,以下测试用例显示错误:

nums = [3,2,1]

Output received : [3,1,2]

Expected Output : [1,2,3]

我无法找出我的代码哪里出错了。另外,如果在下面的代码片段中,如果我从for循环中删除'int',那么没有测试用例通过。

else{
            for(l = n-1 ; l > i ; l--){
                if(nums[l]>nums[i])
                break;
            }
            swap(nums[i], nums[l]);
            reverse(nums.begin() + i + 1 , nums.end());
        }

我得到了以下输出:

nums =
[1,2,3]
Output
[3,1,2]
Expected
[1,3,2]

nums =
[1,1,5]
Output
[5,1,1]
Expected
[1,5,1]
vuv7lop3

vuv7lop31#

你的代码中有两个小问题,导致错误的输出。
在顶部,您在完整函数的范围内定义一些变量:
int n = nums.size(), i, l;
请注意:你应该总是初始化所有的变量。你的编译器会发出一个警告并告诉你。但这不是这个错误的原因。
在两个for循环中,你定义了新的变量'i'和'l',它们将在函数作用域中隐藏相同的变量。它们现在是不同的变量。在for循环之后,它们连同它们的值一起消失。
只要使用你在函数作用域中定义的变量,它就可以工作了。
请参阅:

#include <iostream>
#include <vector>
#include <algorithm>

class Solution {
public:
    void nextPermutation(std::vector<int>& nums) {

        int n = nums.size(), i, l;
        for (i = n - 2; i >= 0; i--) {  // New definition of variable i hides outer definition of i
            if (nums[i] < nums[i + 1])
                break;
        }
        if (i < 0) {
            std::reverse(nums.begin(), nums.end());
        }
        else {
            for (l = n - 1; l > i; l--) { // New definition of variable l hides outer definition of l
                if (nums[l] > nums[i])
                    break;
            }
            std::swap(nums[i], nums[l]);
            std::reverse(nums.begin() + i + 1, nums.end());
        }
    }
};

int main() {
    auto print = [](const std::vector<int>& v) { for (int i : v)std::cout << i << ' '; std::cout << '\n'; };
    std::vector v{ 3,2,1 };
    Solution solution;

    for (int k = 0; k < 10;++k) {
        solution.nextPermutation(v);
        print(v);
    }
}

相关问题