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
arrusingarr.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 missing32in 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
elementCountsmap: 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
ntimes, we skip it.
- If its count is less than
- Preserves order: Since we process elements in their original sequence, the result maintains the input order while enforcing the
Noccurrence 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
相关产品推荐
相关产品推荐

