编写程序在被调函数中删去一维数组中所有相同的数,使之只剩一个,被调函数返回删除后数组中的数据的个数

例如:原数组:4,4,4,6,7,7,7,9,9,9,12,12,24,34,34,34,56,67,78,90删除后:4,6,7,9,12,24,34,56,67,78,90

int main()
{
int a[20]={4,4,4,6,7,7,7,9,9,9,12,12,24,34,34,34,56,67,78,90};
int i=0,j=0,k=0,b[20];//b[]为保存不相同的数组成员
for(i=0;i<20;i++)//遍历每个数组成员
{
for(j=0;j<k;j++)//数组成员与不同数组成员比较
{
if(b[j]==a[i])//如果与不同数组比较有相同者,跳出,进行下一个数组成员比较
break;
}
if(j==k)//如果与不同数组的成员都不同,则加入不同数组;
{
b[k]=a[i];
k++;
}
}
for(i=0;i<k;i++)
printf("%d,",b[i]);
getchar();
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-12-27
#include <stdio.h>
//删除当前位置的数据
void deleteCurrent(int array[],int index,int length)
{
int i=index;
while (i<length) {
array[i]=array[i+1];
i++;
}
}
//删除当前位置后,与本数据相同的数据
int deleteOthers(int index,int array[],int length)
{
int theIndex=index+1,sum=0,theLength=length;
while (theIndex<theLength) {
if (array[index]==array[theIndex]) {
sum++;
deleteCurrent(array,theIndex,theLength);
theLength--;
}
theIndex++;
}
return sum;
}
//显示数组数据
void display(int array[],int length)
{
int index=0;
while (index<length) {
printf("%d ",array[index]);
index++;
}
printf("\n");
}
//删除冗余的数据
void deleteRedundency(int array[],int length)
{
display(array, length);
int theLength=length;
int index=0,deleteNumbers=0;
while (index<theLength) {
deleteNumbers=deleteOthers(index,array, theLength);
theLength=theLength-deleteNumbers;
index++;
index=index-deleteNumbers;
}
display(array,theLength);
}
int main(int argc, constchar * argv[])
{
// insert code here..
int array[20]={4,4,4,6,7,7,7,9,9,9,12,12,24,34,34,34,56,67,78,90};
deleteRedundency(array, 20);
return0;
}
第2个回答  2012-12-27
java Ok吗?

package org.jivesoftware.spark.plugin.flashing;

import java.util.ArrayList;
import java.util.List;

import sun.security.util.Length;

public class ZhiDao1 {

public static int getCount(int[] intArray){
List<Integer> temp = new ArrayList<Integer>();
for(int i : intArray){
if(temp.size()==0){
temp.add(i);
}else{
for(int j=0;j<temp.size();j++){
if(!isContain(temp, i)){
temp.add(i);
}
}
}
}
return temp.size();
}
public static boolean isContain(List<Integer> list,int i){
boolean result=false;
for(int j=0;j<list.size();j++){
if(list.get(j)==i){
result=true;
}
}
return result;
}

public static void main(String[] args){
int[] array={4,4,4,6,7,7,7,9,9,9,12,12,24,34,34,34,56,67,78,90};
System.out.println(getCount(array));
}
}
相似回答