c语言中如何删除数组中的重复元素
把你写的代码贴出来 ? 重新分配个一样大小的数组,把不重复的数组存入第2个数组中即可。#include <stdio.h>
#define MAX 8
int main(void)
{
char a = {'1', '2', '3', '2', '5', '4', '5', '6'};
char b = {'\0'}; // 初始化0
int i, j;
for(i=0; i<MAX; i++)
{
j=0;
while(b != '\0')
{
if (b == a)
break;
j++;
}
if (b == '\0')
b = a;
}
for(i=0; i<MAX; i++)
{
printf("%c ", b);
}
printf("\n");
return 0;
} 检测到相同元素就把之后的所以元素都向前移一位 检测到相同元素就把之后的所有元素都向前移一位 本帖最后由 bin554385863 于 2019-11-12 01:41 编辑
{:10_250:} {:10_250:}
看错人了
类似的问题好几个人问,弄混了 本帖最后由 bin554385863 于 2019-11-12 01:41 编辑
{:10_266:} MMP ? 本帖最后由 jackz007 于 2019-11-15 17:32 编辑
#include <stdio.h>
int del_duplicate(int * d , int n)
{
int b , e , i , j , k , m ;
for(m = n , i = 1 ; i < m ; i ++) {
b = d ;
for(j = i ; j < m ;) {
for(e = 0 ; d == b && j < m ; e ++ , j ++) ;
if(e) {
for(k = j - e ; k < m ; k ++) d = d ;
m -= e ;
} else {
j ++ ;
}
}
}
return m ;
}
int main(void)
{
int a[] = {1 , 2 , 3 , 2 , 5 , 4, 2 , 2 , 2 , 1 , 5 , 6} ;
int k , n , m ;
n = 12 ;
m = del_duplicate(a , n) ;
for(k = 0 ; k < m ; k ++) printf(" %d" , a) ;
return 0 ;
}
编译运行实况:
C:\Bin>g++ -o x x.c
C:\Bin>x
1 2 3 5 4 6
C:\Bin> 遍历过一个没访问的字符后,用一个标志位记为1,后面的字符访问时,如果碰到标志位为1.就删除,时间复杂度O(n)。{:5_92:} ba21 发表于 2019-11-10 12:03
重新分配个一样大小的数组,把不重复的数组存入第2个数组中即可。
老哥,这一步不太懂,char b = {'\0'}; // 初始化0。初始化o是什么意思,数组b里是元素0吗 Jjkkll987987 发表于 2019-11-21 17:41
老哥,这一步不太懂,char b = {'\0'}; // 初始化0。初始化o是什么意思,数组b里是元素0吗
初始化 零 不懂? ba21 发表于 2019-11-21 18:23
初始化 零 不懂?
晓得了,这是字符串数组,才学到数字数组 #include <stdio.h>
#include <string.h>
#include <malloc.h>
void func(char *str)
{
size_t sz = strlen(str), s = 0;
for (size_t i = 0; i < sz; i++)
{
for (size_t j = 0; j < i; j++)
{
if (str < str)
{
char t = str;
*(str + j) = str;
*(str + i) = t;
}
}
}
char *tmp = (char*)malloc(sizeof(char)*(sz + 1));
tmp = '\0';
for (size_t i = 0; i < sz; i++)
{
if (str != str)
{
*(tmp + s) = str;
s++;
}
}
strcpy(str, tmp);
free(tmp);
}
int main(int argc, char const *argv[])
{
char str[] = "9988774455666aaa6332ddddf###%^%###210";
printf("源字符串: %s\n", str);
func(str);
printf("去重之后: %s", str);
return 0;
}
===============================================
Microsoft Windows [版本 10.0.18363.476]
(c) 2019 Microsoft Corporation。保留所有权利。
E:\Users\admin\Documents\VScode\Code>c:\Users\admin\.vscode\extensions\ms-vscode.cpptools-0.26.1\debugAdapters\bin\WindowsDebugLauncher.exe --stdin=Microsoft-MIEngine-In-mcljrnk1.wqr --stdout=Microsoft-MIEngine-Out-whpecix3.2dx --stderr=Microsoft-MIEngine-Error-mjixho3t.n42 --pid=Microsoft-MIEngine-Pid-gocqnrb3.nuk --dbgExe=D:\MinGW\bin\gdb.exe --interpreter=mi
源字符串: 9988774455666aaa6332ddddf###%^%###210
去重之后: #%0123456789^adf
E:\Users\admin\Documents\VScode\Code> 本帖最后由 笨小孩丶 于 2019-12-3 15:24 编辑
#include <stdio.h>
#include <conio.h>
int main()
{
int a={1, 2, 3, 4, 5, 5, 6, 4, 3, 8};
int b;
int i,j,count=1,num=0;
b=a;
while(count<10)
{
for(i=0;i<count;i++)
{
if(a== b )
{
num++;
break;
}
else
{
continue;
}
}
if(i==count)
{
b=a;
}
count++;
}
for (j=0;j<count-num;j++)
{
printf("%d ",b);
}
return 0;
}
页:
[1]