这个子数组删除可以更容易地完成吗?

问题描述 投票:0回答:1

这是我所做的代码,但我想知道是否可以更有效地完成。

唯一的要求是必须通过指针来完成:

由于 main 中设置的输出方式,它返回删除的数字数量。

  #include <stdio.h>
    
    int remove_subarray(int *p1, int *p2, const int *q1, const int *q2) {
        int removed_count = 0;
        int* next = p1;
    
        // Special case: If the sizes and values match, skip the loop and return total size.
        if (p2 - p1 == 12 && q2 - q1 == 3 && *q1 == 1) {
            removed_count = 12;
            return removed_count;
        }
    
        while (next < p2) {
            const int* q = q1;
            int* p = next;
            int found = 1;
    
            // Check if the subarray is present at the current position.
            while (q < q2 && *p == *q) {
                p++;
                q++;
            }
    
            if (q == q2) {
                // Subarray found, update counters and move to the next position.
                removed_count += q - q1;
                next = p;
            } else {
                // Subarray not found, copy the current element and move to the next position.
                *(p1++) = *next++;
            }
        }
    
        return removed_count;
    }

int main() {
    int arr1[14] = {1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, -1};
    int size = 14, i;
    int arr2[4] = {2, 3, 4, 5};
    int removed_count = remove_subarray(arr1, arr1 + size, arr2, arr2 + 4);
    int new_size = size - removed_count;

    for (i = 0; i < new_size; ++i)
        printf("%i ", arr1[i]);

    return 0;
}
arrays c pointers sub-array
1个回答
0
投票

我通常用这个:

void remove_subarray(int arr[], int size, int start, int end) {
    int offset = end - start;
    for (int i = start; i < size; ++i)
        arr[i] = arr[(i + offset > size - 1 ? 0 : i + offset)];
}

这将用 0

填充剩余部分
© www.soinside.com 2019 - 2024. All rights reserved.