You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Codewars题目代码异常:基础测试通过但随机测试结果不符求助

Fixing Your deleteNth Function Issues

Let's break down why your current code is failing random tests and how to fix it.

Problems with Your Current Code

  • Modifying the vector while iterating over it: When you erase elements from arr using arr.erase() during nested loops, you invalidate the iterators used by range-based for loops. This causes elements to shift positions, leading to incorrect indices being targeted for erasure (like the missing 32 in your test case).
  • Flawed counting logic: Your nested loops re-scan the entire modified vector for each element, meaning counts are based on the current state of the vector (not the original order). This leads to inconsistent erasures—sometimes you'll erase too many instances of an element, other times not enough.
  • Inefficient O(n²) complexity: The nested loops are unnecessary and will perform poorly for large input arrays.

Correct Approach: Track Counts in a Single Pass

Instead of modifying the original vector, build a new result vector while keeping track of how many times each element has been added so far. Using a hash map to track counts ensures we stay within the N limit and preserve the original order.

Corrected Code

#include <vector>
#include <unordered_map>

std::vector<int> deleteNth(std::vector<int> arr, int n) {
    std::vector<int> result;
    std::unordered_map<int, int> elementCounts;
    
    for (int num : arr) {
        // Only add the element if we haven't reached the N limit yet
        if (elementCounts[num] < n) {
            result.push_back(num);
            elementCounts[num]++;
        }
    }
    
    return result;
}

How This Works

  • elementCounts map: This keeps a running tally of how many times each number has been added to the result.
  • Single pass iteration: We loop through the input array once. For each element:
    • If its count is less than n, we add it to the result and increment its count.
    • If we've already added it n times, we skip it.
  • Preserves order: Since we process elements in their original sequence, the result maintains the input order while enforcing the N occurrence limit.

Why This Fixes Your Test Case

In your original code, erasing elements caused index shifts that led to accidental removal of valid elements (like the missing 32). The corrected approach avoids modifying the original array entirely, eliminating index errors. It also accurately tracks occurrences, ensuring you never exceed N instances of any element.

内容的提问来源于stack exchange,提问作者newbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 10:38:13