用Java编写一个程序来删除数组中的重复项,并提供示例或说明如何编写一个程序来查找和删除给定数组中的重复项。
在此Java示例中,我们使用while循环来迭代Dup_Count_arrr。然后,删除重复的项(显示多次的值)并打印最终的数组。
public class DelArrDupes1 {
public static void main(String[] args) {
int i = 0, j, k;
int[] Dup_Count_arr = {10, 15, 25, 10, 8, 12, 10, 15, 55, 10, 60};
int Size = Dup_Count_arr.length - 1;
while(i < Size)
{
j = i + 1;
while(j < Size)
{
if(Dup_Count_arr[i] == Dup_Count_arr[j]) {
k = j;
while(k < Size) {
Dup_Count_arr[k] = Dup_Count_arr[k + 1];
k++;
}
Size--;
j--;
}
j++;
}
i++;
}
System.out.print("\nThe Final Array after Deleting Duplicates = " );
for(i = 0; i < Size; i++)
{
System.out.format("%d ", Dup_Count_arr[i]);
}
}
}
The Final Array after Deleting Duplicates = 10 15 25 8 12 55
使用For循环删除数组重复项的Java程序
package ArrayPrograms;
import java.util.Scanner;
public class DeleteArrayDuplicates2 {
private static Scanner sc;
public static void main(String[] args) {
int Size, i, j, k;
int[] Del_Dup_arr = new int[50];
sc = new Scanner(System.in);
System.out.print("\nPlease Enter the Duplicate Array size : ");
Size = sc.nextInt();
System.out.format("\nEnter Duplicate Array %d elements : ", Size);
for(i = 0; i < Size; i++)
{
Del_Dup_arr[i] = sc.nextInt();
}
for(i = 0; i < Size; i++)
{
for(j = i + 1; j < Size; j++)
{
if(Del_Dup_arr[i] == Del_Dup_arr[j]) {
for(k = j; k < Size; k++) {
Del_Dup_arr[k] = Del_Dup_arr[k + 1];
}
Size--;
j--;
}
}
}
System.out.print("\nThe Final Array after Deleting Duplicates = " );
for(i = 0; i < Size; i++)
{
System.out.format("%d ", Del_Dup_arr[i]);
}
}
}

使用函数删除数组重复项的程序
在此示例代码中,我们创建了一个单独的函数DelDupArItems来查找和删除重复值,并打印最终的数组。
import java.util.Scanner;
public class DelArDupes3 {
private static Scanner sc;
public static void main(String[] args) {
int Sz, i;
int[] Del_Dup_arr = new int[50];
sc = new Scanner(System.in);
System.out.print("\nPlease Enter the size : ");
Sz = sc.nextInt();
System.out.format("\nEnter %d elements : ", Sz);
for(i = 0; i < Sz; i++)
{
Del_Dup_arr[i] = sc.nextInt();
}
DelDupArItems(Del_Dup_arr, Sz);
}
public static void DelDupArItems(int[] Del_Dup_arr, int Sz) {
int i, j, count = 0;
int[] x = new int[50];
for(i = 0; i < Sz; i++)
{
for(j = 0; j < count; j++)
{
if(Del_Dup_arr[i] == x[j]) {
break;
}
}
if(j == count) {
x[count] = Del_Dup_arr[i];
count++;
}
}
System.out.print("\nThe Final Array = " );
PrintArElem(x, count);
}
public static void PrintArElem(int[] arr, int sz) {
int i;
for(i = 0; i < sz; i++)
{
System.out.format("%d ", arr[i]);
}
}
}
Please Enter the size : 12
Enter 12 elements : 10 20 30 10 40 10 50 20 60 40 70 30
The Final Array = 10 20 30 40 50 60 70