c++ - 输出不是预期的
问题描述
这是来自 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]
解决方案
我看到你在这里有两个嵌套循环。您可以使用单个循环来实现您想要做的事情。只需使用频率阵列。我在这里使用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
推荐阅读
- typescript - 如何避免打字稿中的if-else多次检查(意大利面条代码)
- mysql - MySQL create table 语句包含每个 char、varchar 和 text 列的冗余排序规则声明是否正常?
- ajax - WP 未定义 WP_CONTENT_DIR
- mysql - SQL获取由表中另一列分组的给定日期之间的日期范围
- javascript - 如果 jquery 中的语句没有按预期运行
- c# - Mongo db sha 1 到 sha256
- spring-boot - log4j2 未写入 xml 文件中指定的日志文件
- r - lapply() 在数据框列表上
- android - 如何用 mockito 存根这个方法
- azure - 当新数据库已经存在于我们的 UAT 和 Prod 环境中时,为我们的 QA 环境定义新数据库