題
此方法將檢查數字 'n'
在方法中存盤的整數陣列中不止一次
如果在陣列中重復,則回傳 true 和 false
如果不
*/
我的代碼:
for (int i = 0; i < myYears.length; i ) {
for (int j = 0; j < myYears.length; j ) {
// got the duplicate element
System.out.println("Got dublicate");
return true;
}
}
return false;
然而,無論輸入如何,我得到的都是“得到重復”。
編輯 1
package main;
公共類 Array1 {
public static void main(String[] args) {
findMoreThanOneInArray(1231); // test will return true
} // end main
/*
* This method will check to see if number 'n'
* is in the array of integers stored in the method more than once
*
* It returns true if it is duplicated in the array and false
* if not
*/
private static boolean findMoreThanOneInArray(int n) {
boolean result = false; // default the search to false
int[] myYears = { 2176, 2311, 2472, 2131, 2046, 2209, 2473, 2364, 2116, 2462, 2405, 2032, 2226, 2223, 2065, 2336, 2372, 2084, 2000, 2074, 2263, 2092, 2485, 2229, 2222, 2369, 2130, 2381, 2487, 2271, 2432, 2011, 2264, 2328, 2251, 2002, 2036, 2410, 2166, 2022, 2064, 2168, 2122, 2409, 2100, 2276, 2361, 2042, 2387, 2211, 2479, 2327, 2044, 2319, 2308, 2265, 2368, 2021, 2325, 2395, 2256, 2086, 2449, 2171, 2098, 2117, 2468, 2338, 2214, 2314, 2204, 2073, 2045, 2295, 2020, 2447, 2233, 2060, 2094, 2383, 2457, 2260, 2224, 2105, 2261, 2405, 2472, 2477, 2253, 2175, 2107, 2441, 2379, 2027, 2386, 2090, 2496, 2280, 2285, 2117 };
/*
* you code goes here
* return true if n is duplicated in the array, false otherwise
*/
for (int i = 0; i < myYears.length; i ) {
for (int j = i 1 ; j < myYears.length; j ) {
if (myYears[i] == myYears[j]) {
System.out.println("Got dublicate");
return true;
}
}
}
return false;
} // end of method
} // 結束類
編輯 2
for (int i = 0; i < myYears.length; i ) {
if (myYears[i] == n) {
System.out.println("Got dublicate");
return true;
}
}
System.out.println("false");
return false;
Edit 2 通過了除一項之外的所有測驗,n = 2222 的值;誰能建議為什么?
通過了除一項外的所有測驗
uj5u.com熱心網友回復:
我想這就是你正在尋找的......
int count = 0;
for (int i = 0; i < myYears.length; i ) {
if (myYears[i] == n) {
count ;
}
}
if (count >= 2) {
System.out.println("true");
return true;
}
System.out.println("false");
return false;
count如果在陣列中找到給定的值,此代碼基本上每次都會將變數增加1。在 for 回圈之后,我們檢查變數count是否大于或等于該值2(因為我們需要知道給定的數字n是否出現多次)
uj5u.com熱心網友回復:
我推薦弗洛伊德的龜兔賽跑演算法。基本上你像圖表一樣對待陣列并找到回圈 - 這是你的重復數字
https://dev.to/alisabaj/floyd-s-tortoise-and-hare-algorithm-finding-a-cycle-in-a-linked-list-39af
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/363283.html
