else 也就是 sorted, 那要做什麼呢? 就是要記錄結果到 count[] 陣列, 因為已經沒有右邊比左邊大的 case 了
a. 記錄結果到 count[] 陣列 .=> 這就要利用到 items[l].idx 了 so count[items[l.idx]] += rightCount
b. 把 l 目前內容加入, item[l++] 加到 temp
ex 5, 2 .=> 2, 5 ., rightCount++, 塞了 2 到 temp[0]
while (l <= mid && r <= right) {if (items[l].val> items[r].val) { // l > r, means move r to l, so insert r data to temp, // and add rightcount , ex 5 2 => 2 5, but rightCount should++ rightCount++; temp[tempIdx++] = items[r++]; } else { // if l < r, it is sorted, ex: 2 5, // cal count result(count[l index] += rightCnt), // insert l data to temp count[items[l].idx] += rightCount; temp[tempIdx++] = items[l++]; } }
第二個 while 就跟 第一個 while else 其實內容一樣 ( 因為是 l <= mid)
while (l <= mid) { // insert remained l data, and cal count, (insert l data means cal result!) count[items[l].idx] += rightCount; temp[tempIdx++] = items[l++]; }
ex 5 2 .=> 2, 5 之後, 還剩下 5, 所以塞 5 到 temp[1] .( while l <= mid
while (l <= mid) { // insert remained l data, and cal count, (insert l data means cal result!) count[items[l].idx] += rightCount; temp[tempIdx++] = items[l++]; }while (r <= right) { // insert remained r data temp[tempIdx++] = items[r++]; }// finally put sorted temp data to itemsfor (int p =0; p <temp.length; p++) { items[left + p] = temp[p]; }
最後把 temp 結果(sort 的), 更新到原本 items 中
classSolution {privateclassItem { int val;int idx;publicItem(int val,int idx) {this.val= val;this.idx= idx; // for count use } }publicList<Integer> countSmaller(int[] nums) {int n =nums.length;int[] count =newint[n];Item[] items =newItem[n];for (int i =0; i < n; i++) { items[i] =newItem(nums[i], i); }mergeSort(items,0, n -1, count);List<Integer> result =newArrayList<>();for (int cnt : count) {result.add(cnt); }return result; }privatevoidmergeSort(Item[] items,int left,int right,int[] count) {if (left >= right) return;int mid = (right + left) >>1;mergeSort(items, left, mid, count);mergeSort(items, mid +1, right, count);merge(items, left, mid, right, count); }privatevoidmerge(Item[] items,int left,int mid,int right,int[] count) {Item[] temp =newItem[right - left +1];int tempIdx =0;int l = left;int r = mid +1;int rightCount =0;while (l <= mid && r <= right) {if (items[l].val> items[r].val) { // l > r, means move r to l, so insert r data to temp, // and add rightcount , ex 5 2 => 2 5, but rightCount should++ rightCount++; temp[tempIdx++] = items[r++]; } else { // if l < r, it is sorted, ex: 2 5, // cal count result(count[l index] += rightCnt), // insert l data to temp count[items[l].idx] += rightCount; temp[tempIdx++] = items[l++]; } }while (l <= mid) { // insert remained l data, and cal count, (insert l data means cal result!) count[items[l].idx] += rightCount; temp[tempIdx++] = items[l++]; }while (r <= right) { // insert remained r data temp[tempIdx++] = items[r++]; }// finally put sorted temp data to itemsfor (int p =0; p <temp.length; p++) { items[left + p] = temp[p]; } }}