用 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