用 Java 编写一个程序以在整型数组中查找第一个不重复的数字?
若要查找数组中的第一个不重复数字:
- 构建一个计数数组来存储给定数组中每个元素的计数,长度相同,且所有元素的初始值均为 0。
- 将数组中的每个元素与该元素之外的所有其他元素进行比较。
- 如果出现匹配,则在计数数组中增加该元素的值。
- 获取计数数组中第一个 0 的索引,然后打印该索引处的输入数组元素。
示例
import java.util.Arrays;
public class NonRpeatingArray {
public static void main(String args[]) {
int array[] = {114, 225, 669, 996, 336, 6547, 669, 225, 336, 669, 996, 669, 225 };
System.out.println("");
//Creating the count array
int countArray[] = new int[array.length];
for(int i=0; i<array.length; i++) {
countArray[i] = 0;
}
for(int i=0; i<array.length; i++) {
for(int j=0; j<array.length;j++) {
if(i!=j && array[i]==array[j]) {
countArray[i]++;
}
}
}
System.out.println(Arrays.toString(countArray));
//First non-repeating element in the array
for(int i=0; i<array.length; i++) {
if(countArray[i]==0) {
System.out.println(array[i]);
break;
}
}
}
}输出
[0, 2, 3, 1, 1, 0, 3, 2, 1, 3, 1, 3, 2] 114
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP