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

C语言数组去重问题:求两整数数组交集时如何去除重复元素

Fixing Your Array Intersection Duplicate Removal & Stalling Issue

Hey there! Let's break down why your code is stalling and fix that duplicate problem without using any external libraries or custom functions.

First, Why Your Code Is Stalling

The issue is in your duplicate check loop—you've got a typo that creates an infinite loop:

for (int k = j; j < count; i++) {
    intersection[k] = intersection[k + 1];
}

Look at that loop: you're using i++ instead of k++, and your condition checks j < count (which never changes here). This means i will keep incrementing forever, causing your program to freeze.

Fix 1: Repair the Existing Duplicate Removal

If you want to stick with your original approach (collect all intersections first, then deduplicate), here's the corrected duplicate check code:

// Correplicate check
int count = 0;
// First, count how many valid elements are in intersection (since '\0' isn't a safe marker for integers)
for (int i = 0; i < SIZE; i++) {
    if (intersection[i] != 0) { // Note: If 0 is a valid input, use a unique sentinel like INT_MIN (include <limits.h> if needed)
        intersection[count++] = intersection[i];
    }
}

// Now deduplicate the valid elements
for (int i = 0; i < count; i++) {
    for (int j = i + 1; j < count; j++) {
        if (intersection[i] == intersection[j]) {
            // Shift elements left to overwrite the duplicate
            for (int k = j; k < count - 1; k++) {
                intersection[k] = intersection[k + 1];
            }
            count--;
            j--; // Decrement j to recheck the new element at this position
        }
    }
}

Also, initializing intersection with '\0' (which is 0) is risky if 0 is a valid input value. If your input can include 0, use a sentinel value like INT_MIN (from <limits.h>) instead, or track valid elements with a counter from the start.

Fix 2: Avoid Duplicates While Collecting Intersections (More Efficient)

A better approach is to check for duplicates as you build the intersection array, so you don't have to clean up later. Here's a full revised version of your code:

#include <stdio.h>
#define SIZE 10

int main(void){
    //Initialization
    int array1[SIZE];
    for (int i = 0; i < SIZE; i++) {
        printf("Input integer %d of set A: ", i + 1);
        scanf("%d", &array1[i]);
    }

    int array2[SIZE];
    for (int i = 0; i < SIZE; i++) {
        printf("Input integer %d of set B: ", i + 1);
        scanf("%d", &array2[i]);
    }

    int intersection[SIZE];
    int inter_len = 0; // Track how many unique intersection elements we've added

    // Intersection check + duplicate prevention in one step
    for (int i = 0; i < SIZE; i++) {
        int is_in_array2 = 0;
        // Check if current array1 element exists in array2
        for (int j = 0; j < SIZE; j++) {
            if (array1[i] == array2[j]) {
                is_in_array2 = 1;
                break;
            }
        }

        // If it's in array2, check if it's already in the intersection array
        if (is_in_array2) {
            int already_exists = 0;
            for (int k = 0; k < inter_len; k++) {
                if (array1[i] == intersection[k]) {
                    already_exists = 1;
                    break;
                }
            }
            // Only add it if it's not already present
            if (!already_exists) {
                intersection[inter_len++] = array1[i];
            }
        }
    }

    // Printing the unique intersection
    printf("Unique intersection elements:\n");
    for (int i = 0; i < inter_len ; i++) {
        printf("%d\n", intersection[i]);
    }

    return 0;
}

This version:

  • Uses a counter inter_len to track valid elements (no risky sentinel values)
  • Checks if an element is already in the intersection before adding it, so duplicates never get stored
  • Eliminates the need for a separate deduplication step, making the code cleaner and faster

Key Notes

  • Never use '\0' as a sentinel for integer arrays unless you're sure 0 won't be a valid input value.
  • When shifting elements to remove duplicates, always decrement j after shifting—this ensures you don't skip checking the new element that moves into j's position.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 16:52:48