我的函數沒有返回正確的答案。我的任務是在一個數組是相同的,彼此相鄰這裏算兩個數字是一個例子:計算數組中相同元素的唯一相鄰對的數量
array_1 = {1,2,2,3,4,4,2}; ans = 2
array_2 = {2,2,3,4,4}; ans = 2
array_3 = {1,1,1,1,1,1,1}; ans = 1
array_4 = {1,2,3,4,2}; ans = 0
這裏是我的功能。觀察到的結果作爲評論給出。
public class countClampsTest
{
public static void main(String[] args)
{
int array_1[] = {1,2,2,3,4,4,2}; // expected result: 2
int array_2[] = {2,2,3,4,4}; // expected result: 2
int array_3[] = {1,1,1,1,1,1,1}; // expected result: 1
int array_4[] = {1,2,3,4,2}; // expected result: 0
System.out.println(countClamps(array_1)); // Returns 2
System.out.println(countClamps(array_2)); // Returns 1
System.out.println(countClamps(array_3)); // Returns 1
System.out.println(countClamps(array_4)); // Returns 0
}
static int countClamps(int[] arr) {
int result = 0;
int nextNext = 0;
for (int current = 0; current < arr.length - 1; current++) {
for (int next = current; next <= current + 1; next++) {
nextNext = next + 1;
if(nextNext >= arr.length) {
nextNext = arr.length -1;
}
if (arr[current] == arr[next] && current != next) {
if(arr[next] != arr[nextNext]) {
result++;
} else if(arr[next] == arr[nextNext] && arr.length % 2 == 0) {
result = 1;
}
}
}
}
return result;
}
}
爲什麼數組1的答案是3?只有兩對數字相鄰?您可能需要更多地解釋這個... – BretC
您的任務描述不清楚。爲什麼第一個答案應該是3?我看到兩對數字「彼此相同和相鄰」,即「2,2」和「4,4」,那麼3的答案如何? – Andreas
謝謝@BretC它應該被2編輯修正 – Cham