gpt4 book ai didi

c - 从给定数组中删除元素

转载 作者:行者123 更新时间:2023-11-30 18:15:17 25 4
gpt4 key购买 nike

我正在 Leetcode 上做一道题。问题是,给定一个数组和一个值,删除该值的所有实例并返回新的长度。或者您可以阅读 here :

int removeElement(int* nums, int numsSize, int val) {
int *nums_copy;
int count = 0;
int actual_count = 0;


while (actual_count < numsSize) {

if (nums[actual_count] != val) {
nums_copy[count] = nums[actual_count];
count++;
nums_copy = realloc(nums_copy, sizeof(int)* count);
}
actual_count++;
}

nums = nums_copy;
return actual_count;
}

当我尝试使用 [1, 2, 2, 3], 2 测试它时,输出为 [1, 2, 2, 3] 而预期输出为 [1, 3]

最佳答案

首先,你不需要重新分配,问题是要删除原地的值。其次,您需要做的就是简单地遍历数组并将其在遇到搜索值时向左移动一位。并减少结果计数。

关于c - 从给定数组中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34666097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com