如何在 java 中从数组中提取唯一值?
要提取数组中的唯一值,需要将数组的每个元素与所有剩余元素比较,如果匹配,则获得了重复元素。要实现此目的,需要使用两个循环(嵌套),其中内循环从 i+1(i 是外循环的变量)开始,以避免比较中的重复。
示例
import java.util.Arrays;
import java.util.Scanner;
public class DetectDuplcate {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array that is to be created::");
int size = sc.nextInt();
int[] myArray = new int[size];
System.out.println("Enter the elements of the array ::");
for(int i=0; i<size; i++) {
myArray[i] = sc.nextInt();
}
System.out.println("The array created is ::"+Arrays.toString(myArray));
System.out.println("indices of the duplicate elements :: ");
for(int i=0; i<myArray.length; i++) {
for (int j=i+1; j<myArray.length; j++) {
if(myArray[i] == myArray[j]) {
System.out.println(j);
}
}
}
}
}输出
Enter the size of the array that is to be created :: 6 Enter the elements of the array :: 87 52 87 63 41 63 The array created is :: [87, 52, 87, 63, 41, 63] indices of the duplicate elements :: 2 5
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP