<?php /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * @param data int整型一维数组 * @return int整型 */ function InversePairs( $data ) { // write code here if (empty($data)) return 0; return InversePairsCore($data, 0, count($data) - 1); } function InversePairsCore(&$array, $low, $high) { if ($low == $high) return 0; $mid = floor(($low + $high) / 2); $leftCount = InversePairsCore($array, $low, $mid); $rightCount = InversePairsCore($array, $mid + 1, $high); $count = mergeArray($array, $low, $mid, $high); return ($leftCount + $rightCount + $count)%1000000007; } function mergeArray(&$array, $low, $mid, $high) { $i = $low; $j = $mid + 1; $count = 0; while($i <= $mid && $j <= $high) { if ($array[$i] > $array[$j]) { $tmp[] = $array[$i++]; $count += $high - $j + 1; } else { $tmp[] = $array[$j++]; } } while($i <= $mid) { $tmp[] = $array[$i++]; } while($j <= $high) { $tmp[] = $array[$j++]; } for ($k = 0; $k < count($tmp); $k++) { $array[$low + $k] = $tmp[$k]; } return $count; }
也是看了前面的大神们的思路,自己用php实现了下。就是用归并排序对数组进行排序的时候顺便取做一下判断,同时记录判断的结果。而这个结果最后就是我们需要的。我觉得需要注意的一个点是,两个子序列比较的时候,如果两个子序列都是升序,那么满足条件后的count就是mid,但是如果是降序,那么满足条件后的count是j+1