编译正常但提交后出现RUN_ERROR:数组最近重复元素程序排查
Hey there! Let's dig into why your code is hitting a RUN_ERROR when submitted. I've gone through your implementation and spotted a critical issue that's causing this runtime crash:
Your code uses a[abs(a[i])] to mark whether an element has appeared before, but this creates a severe array out-of-bounds error:
- The array
ahas a size ofn(the user-input length of the array), but the problem allows element values up to10^5. - If
nis smaller than any element's value (e.g.,n=5but an element is10), accessinga[10]will reach memory outside the array's allocated space, which directly triggers a runtime error—this is exactly the RUN_ERROR you're seeing.
Example of the Issue
Suppose the user inputs n=3 followed by elements [2, 3, 4]. When processing the third element 4, your code tries to access a[4], but the array only has indices 0, 1, and 2. This invalid memory access crashes the program.
To fix this, you need a marker array that can cover all possible element values (1 to 10^5), instead of repurposing the input array (which might be too small). Here's the corrected version:
#include<stdio.h> #include<stdlib.h> #include<stdbool.h> void input(int *x); int main(){ int n; input(&n); // Create a boolean array to track seen elements (covers 1 to 100000) bool *seen = (bool*)calloc(100001, sizeof(bool)); if (seen == NULL) { // Handle memory allocation failure return 1; } int num; for(int i=0;i<n;i++){ if (scanf("%d",&num)!=1) { free(seen); // Clean up memory before exiting return 0; } if (num > 100000 || num < 1) { free(seen); return 0; } if (seen[num]) { // Found the first duplicate printf("%d", num); free(seen); return 0; } else { seen[num] = true; // Mark element as seen } } free(seen); // Release allocated memory return 0; } void input(int *x){ if (scanf("%d",x)!=1) exit(0); if (*x > 100000 || *x <1) exit(0); }
- Used
callocto initialize the marker array tofalseautomatically, which is cleaner than manual initialization. - Removed the need to store the entire input array—we only need to check duplicates as we read each element.
- Added memory cleanup with
free()to avoid memory leaks. - Used a
boolarray instead of an integer array to save memory (1 byte per element vs. 4 bytes for integers).
Your original code also had a minor logical flaw: if an element's value equals an array index, it could incorrectly mark elements as duplicate, but the out-of-bounds access was the immediate cause of the RUN_ERROR.
内容的提问来源于stack exchange,提问作者Nguyen Huu Tien K14 HCM

