gpt4 book ai didi

c - 清除数组中重复项的函数

转载 作者:太空宇宙 更新时间:2023-11-03 23:41:41 25 4
gpt4 key购买 nike

我正在尝试创建一个函数来清除数组中重复的数字,但似乎我无法弄清楚我缺少什么来删除重复项。只是为了更清楚:该函数不应变为无效。

[1,2,3,3,4] -> [1,2,3,4]
[4,2,5,1]->[4,2,5,1]
[32,21,2,5,2,1,21,4]->[32,21,2,5,1,4]

我的数组中不应该是空格,函数应该返回cleaned 数组中的唯一元素,其中 cleaned 定义为“整数的非重复”

#include <stdio.h>

int generateUniqeList(int *list, int length);

int main()
{
int list[6] = { 5, 5, 4, 3, 2, 1 };
int duplicate = generateUniqeList(list, 6);

for (int i = 0; i < 6; i++)
{
printf("%d\n", list[i] - 1); //Here i am able to change the value of the duplicates with the - 1
}
getchar();

return 0;
}


int generateUniqeList(int *list, int length)
{
int duplicate = 0;

for (int i = 0; i < length; i++)
{
if (list[i] == list[i])
duplicate = list[i];
}
return duplicate;
}

最佳答案

#include <stdio.h>
#include<string.h>


void generateUniqeList(int *list, int length);

int main()
{
int list[6] = { 5, 5, 4, 3, 2, 1 };
generateUniqeList(list, 6);

for (int i = 0; i < 6; i++)
{
printf("%d", list[i]);
//Here i am able to change the value of the duplicates with the - 1
}
putchar('\n');

return 0;
}


void generateUniqeList(int *list, int length){
int i ,j,k;
for (i = 0; i < length; i++) {
for (j = i + 1; j < length;) {
if (list[j] == list[i]) {
for (k = j; k < length; k++) {
list[k] = list[k + 1];
}
length--;
} else
j++;
}
}

}

关于c - 清除数组中重复项的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43808549/

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