我知道加法是可交換的,因此我想 =在第 46 行使用速記操作執行存盤操作,但只有當我放括號時答案才會有所不同,當我不放括號時我得到錯誤的答案。
該行在合并功能中。
代碼:
public class ProblemA {
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer> (Arrays.asList(1, 3, 2, 3, 1));
int n = arr.size();
//calling mergesort
int total = countPair(arr, n);
System.out.println(total);
}
public static int countPair(ArrayList<Integer> arr, int n) {
int total = mergeSort(arr, 0, n - 1);
return total;
}
public static int mergeSort(ArrayList<Integer> arr, int low, int high) {
//termination condition
if (low >= high) return 0;
//firstly we'll disassociate the elements of array on elementary level
int mid = (low high) / 2;
//we'll store our count value inside the counter variable
int inv = mergeSort(arr, low, mid);
inv = mergeSort(arr, mid 1, high);
inv = merge(arr, low, mid, high);
return inv;
}
public static int merge(ArrayList<Integer> arr, int low, int mid, int high) {
//AIM: make a double loop and traverse through the elements and increase the right side pointer
//whenever condition (arr[i]>2*arr[j] is satisfied)
//int i = 0;
int total = 0;
int j = mid 1;
for (int i = low; i<= mid; i ) {
//looping till we run out the right hand side or condition is not satisfied
while (j<= high && arr.get(i) > 2 * arr.get(j)) {
j ;
} **
* total = (j - (mid 1)); ** * //parenthesis error here
}
//Now we can move to merging part
ArrayList<Integer> temp = new ArrayList<Integer> ();
int left = low, right = mid 1;
while (left<= mid && right<= high) {
if (arr.get(left)<= arr.get(right)) {
temp.add(arr.get(left ));
} else {
temp.add(arr.get(right ));
}
}
//for the last right or left remaining element
while (left<= mid) {
temp.add(arr.get(left ));
}
while (right<= high) {
temp.add(arr.get(right ));
}
//now we can copy the remaining elements from temp list to arr
for (int i = low, k = 0; i<= high; i ) {
arr.set(i, temp.get(k ));
}
return total;
}
}
輸出(帶括號)“總計 = (j-(mid 1))”:
2
輸出(不帶括號)“total = j-mid 1”:
16
uj5u.com熱心網友回復:
發生這種情況是因為如果您使用括號,java 將決定您首先要評估哪個運算式。如果你不使用括號,那么一切都會從左到右執行。例子:
int total=1;
int total1=1;
int total2=1;
total =total1-total2 1;
System.out.println(total);
輸出:2
原因就在這里,運算式被評估為 total=total total1-total2 1; 即總計=1 1-1 1=2;
對于基于括號的運算式,它首先被評估,然后是其他的:-
int total=1;
int total1=1;
int total2=1;
total =(total1-(total2 1));
System.out.println(total);
輸出:0,評估將如下所示:-
total=total (1-(1 1));
total=1 (1-(2));
total=1 (-1);
total=0;
參考:https ://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/474831.html
上一篇:數小時變大,大時變小
下一篇:計算橢圓內具有整數坐標的點數
