首页 > 解决方案 > 输出不是预期的

问题描述

这是来自 codewars.com 的一个问题

给定一个列表和一个数字 N,创建一个新列表,其中包含每个 lst 最多 N 次而不重新排序。例如如果N = 2,输入是[1,2,3,1,2,1,2,3],你取[1,2,3,1,2],去掉下一个[1,2 ] 因为这会导致 1 和 2 在结果中出现 3 次,然后取 3,这会导致 [1,2,3,1,2,3]。

这是我的代码:

std::vector<int> deleteNth(std::vector<int> arr, int n)
{
   int counting = 0;
   int counting2 = 0;
   for (int i : arr)
   {
    for (int j : arr)
    {
     cout << arr.size() << "  " << counting<<"  "<<counting2<<endl;
        if (i == j) 
        {
            ++counting;
            if (counting > n) { arr.erase(arr.begin() + counting2); --counting2; }
        }

        counting2++;
    }
    counting = 0;
    counting2 = 0;
}
return arr;

基本测试没问题。但是当我尝试他们的随机测试时。一团糟。

预期:等于 [ 8, 32, 32, 8, 8, 26, 26, 8, 19, 26, 26, 19, 26, 26, 19, 8, 8, 19, 26, 8, 8, 19, 32 , 32, 26, 50, 19, 32, 32, 32, 19] 实际:[ 8, 32, 32, 8, 8, 26, 26, 8, 19, 26, 26, 19, 26, 26, 19, 8、8、19、26、8、8、19、32、26、50、19、32、32、19]

标签: c++listloops

解决方案


我看到你在这里有两个嵌套循环。您可以使用单个循环来实现您想要做的事情。只需使用频率阵列。我在这里使用std::map是因为未知的数字范围。如果范围已知,您可以使用数组或std::vector让代码在 O(N) 中运行。

#include <iostream>
#include <vector>
#include <map>

std::vector<int> deleteNth(std::vector<int>& arr, int n)
{
    std::map<int, int> freq;
    std::vector<int> result;

    for (int number : arr)
    {
        if (freq[number] >= n)
            continue;

        result.push_back(number);
        freq[number]++;
    }

    return result;
}

int main()
{
    std::vector<int> v{ 1,2,3,1,2,1,2,3 };
    auto result = deleteNth(v, 2);

    for (int i : result)
        std::cout << i << ' ';
}

输出:

1 2 3 1 2 3

推荐阅读