删去一维数组中所有相同的数,使之只剩一个。数组中的数已按由小到大的顺序排列,函数返回删除后数组中数怎么写
1、创建java类,TestEqual
2、编写去重函数,
public static int unique1(int[] nums) {
if (nums.length == 0) {
return 0;
}
Set<Integer> set = new HashSet<Integer>();
int index = 0;
for (int i = 0, len = nums.length; i < len; i++) {
if (set.add(nums[i])) {
nums[index++] = nums[i];
}
}
return index;
}
3、编写打印函数,
public static void printNums(int[] nums, int length) {
for (int i = 0; i < length - 1; i++) {
System.out.print(nums[i] + " ");
}
System.out.println(nums[length - 1]);
}
4、初始化入参数据,int[] str = { 1, 1, 2, 3, 4, 4, 4, 5, 9, 9 },执行代码,consle输出踢重后数据,1,2,3,4,5,9,
#include<stdio.h>
int fun(int *a,int n) { int i,j;
for ( i=j=0;i<n;i++ ) if ( a[i]!=a[j] ) { j++; a[j]=a[i]; }
return j+1;
}
void main() { int a[10]={1,1,2,3,4,4,4,5,9,9},i,n;
for ( i=0;i<10;i++ ) printf("%d ",a[i]); printf("\n");
n=fun(a,10);
for ( i=0;i<n;i++ ) printf("%d ",a[i]); printf("\n");
}
本回答被网友采纳