35. Title Description
Two numbers in an array, if the first number is greater than the latter, then the two numbers form an inverse pair. Enter an array to find the total number of reverse pairs in the array, P. And output the result of P to 1000000007. I.e. output P% 100000007
Enter a description:
Ensure that the same number does not exist in the input array
Data range:
For data of% 50, size < = 10 ^ 4
Size < = 10 ^ 5 for data of% 75
For data of% 100, size < = 2 * 10 ^ 5
Idea: variant of merging algorithm
class Solution {
public:
int InversePairs(vector<int> data) {
if(data.size()==0)
return 0;
vector<int>temp(data);
long long count=process(data,temp,0,data.size()-1);
return count%1000000007;
}
long long process(vector<int> &data,vector<int> &temp,int start,int end)
{
if(start==end)
return 0;
int mid=(start+end)>>1;
long long left=process(temp,data,start,mid);
long long right=process(temp,data,mid+1,end);
int r1=mid,r2=end;
int k=end;
long long count=0;
while(r1>=start && r2>=mid+1)
{
if(data[r1]>data[r2])
{
temp[k--]=data[r1--];
count+=r2-mid;
}
else
temp[k--]=data[r2--];
}
while(r1>=start)
temp[k--]=data[r1--];
while(r2>=mid+1)
temp[k--]=data[r2--];
return count+left+right;
}
};
# -*- coding:utf-8 -*-
import copy
class Solution:
def process(self,data,temp,start,end):
if start==end:
return 0
mid=(start+end)>>1
left=self.process(temp,data,start,mid)
right=self.process(temp,data,mid+1,end)
r1=mid
r2=end
k=end
count=0
while r1>=start and r2>=mid+1:
if data[r1]>data[r2]:
temp[k]=data[r1]
k=k-1
r1=r1-1
count+=r2-mid
else:
temp[k]=data[r2]
k=k-1
r2=r2-1
while r1>=start:
temp[k]=data[r1]
k=k-1
r1=r1-1
while r2>=mid+1:
temp[k]=data[r2]
k=k-1
r2=r2-1
return count+left+right
def InversePairs(self, data):
if len(data)<=1:
return 0
temp=copy.copy(data)
num=self.process(data,temp,0,len(data)-1)
return num%1000000007
# write code here
36 topic description
Enter two linked lists to find their first common node.
Idea: the first linked list has m1 nodes before the common node, the second linked list has m2 nodes before the common node, and the common node has n nodes (at least NULL is the common node).
M1 + N + M2 = M2 + N + M1 indicates that the first common node meets.
After traversing the first list, go to the second list. The second list is the same.
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
ListNode* p1=pHead1;
ListNode* p2=pHead2;
while(p1!=p2)
{
p1=(p1==NULL? pHead2:p1->next);
p2=(p2==NULL? pHead1:p2->next);
}
return p1;
}
};
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
p1=pHead1
p2=pHead2
while p1 != p2:
p1=pHead2 if p1==None else p1.next
p2=pHead1 if p2==None else p2.next
return p1