牛客網 劍指office 陣列中的逆序對

2021-09-24 04:59:49 字數 2066 閱讀 8703

題目:在陣列中的兩個數字,如果前面乙個數字大於後面的數字,則這兩個數字組成乙個逆序對。輸入乙個陣列,求出這個陣列中的逆序對的總數p。並將p對1000000007取模的結果輸出。 即輸出p%1000000007

思路:歸併排序。先將陣列分為若干個長度相等的子陣列,然後在合併子陣列的時候進行排序、並統計逆序對,時間複雜度為歸併排序的o(nlogn)

注:關於data和copy交換的原因:

.在每次的操作中,數值的比較都是採用當前傳入函式中第一項,也就是data;比較的結果都存放到copy中;也就意味著此時copy中是經過此次呼叫的結果。

class solution 

long long helper(vector& data, vector& copy, int start, int end)

int length = (end - start) / 2;

long long left = helper(copy, data, start, start + length);

long long right = helper(copy, data, start + length + 1, end);

int i = start + length;

int j = end;

int copypos = end;

long long count = 0;

while (i >= start&&j >= (start + length + 1))

else

}for (; i >= start; --i)

copy[copypos--] = data[i];

for (; j >= start + length + 1; --j)

copy[copypos--] = data[j];

return count + left + right;

}};

python的解法:

class solution:

def inversepairs(self, data):

length = len(data)

copy =

for num in data:

count = self.helper(data, copy, 0, length-1)

del copy

return count % 1000000007

def helper(self, data, copy, start, end):

if start == end:

copy[start] = data[start]

return 0

length = int((end - start) / 2)

left = self.helper(copy, data, start, start+length)

right = self.helper(copy, data, start+length+1, end)

i = start + length

j = end

copypos = end

count = 0

while (i >= start) and (j >= start + length + 1):

if data[i] > data[j]:

copy[copypos] = data[i]

copypos -= 1

i -= 1

count += j - start - length

else:

copy[copypos] = data[j]

copypos -= 1

j -= 1

while i >= start:

copy[copypos] = data[i]

copypos -= 1

i -= 1

while j >= start + length+1:

copy[copypos] = data[j]

copypos -= 1

j -= 1

return left + right + count

牛客網 劍指office 求1 2 2 n

題目 求1 2 3 n,要求不能使用乘除法 for while if else switch case等關鍵字及條件判斷語句 a?b c 解法一 思路 遞迴求和。class solution 解法二 思路 利用建構函式求解。我們先定義乙個類,接著建立n個該型別的例項,那麼這個建構函式將會被呼叫n次,...

牛客網 劍指office 字串的排列

題目 題目描述 輸入乙個字串,按字典序列印出該字串中字元的所有排列。例如輸入字串abc,則列印出由字元a,b,c所能排列出來的所有字串abc,acb,bac,bca,cab和cba。輸入描述 輸入乙個字串,長度不超過9 可能有字元重複 字元只包括大小寫字母。解法一 思路 python 的解法 同解法...

牛客網 劍指office 資料流中的中位數

題目 如何得到乙個資料流中的中位數?如果從資料流中讀出奇數個數值,那麼中位數就是所有數值排序之後位於中間的數值。如果從資料流中讀出偶數個數值,那麼中位數就是所有數值排序之後中間兩個數的平均值。我們使用insert 方法讀取資料流,使用getmedian 方法獲取當前讀取資料的中位數。思路 首先要理解...