class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
if(intervals.size()==0)
{
return {};
}
sort(intervals.begin(),intervals.end());
vector<vector<int>> merged;
for(int i=0;i<intervals.size();i++)
{
int L=intervals[i][0],R=intervals[i][1];
if(!merged.size() ||merged.back()[1]<L)
{
merged.push_back({L,R});
}
else
{
merged.back()[1]=max(merged.back()[1],R);
}
}
return merged;
}
};
class Solution {
public:
vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {
//寻找最大元素
int upper=*max_element(arr1.begin(),arr1.end());
vector<int> freqency(upper+1);
for(int x:arr1)
{
++freqency[x];
}
vector<int> ans;
for(int x:arr2)
{
for(int i=0;i<freqency[x];i++)
{
ans.push_back(x);
}
//清除
freqency[x]=0;
}
for(int x = 0; x <= upper; ++x)
{
for(int i=0;i<freqency[x];i++)
{
ans.push_back(x);
}
}
return ans;
}
};
class Solution {
public:
//寻找n-k
int quick(vector<int>&a,int l,int r, int index)
{
int q=random(a,l,r);
if(q==index)
{
return a[q];
}
else
{
return q<index ? quick(a,q+1,r,index):quick(a,l,q-1,index);
}
}
//快速排序1寻找中间值
inline int random(vector<int>&a,int l,int r)
{
int i=rand()%(r-l+1)+l;
swap(a[i],a[r]);
return partition(a,l,r);
}
//快速排序2
inline int partition(vector<int>& a, int l, int r) {
int x = a[r], i = l - 1;
for (int j = l; j < r; ++j) {
if (a[j] <= x) {
swap(a[++i], a[j]);
}
}
swap(a[i + 1], a[r]);
return i + 1;
}
int findKthLargest(vector<int>& nums, int k) {
srand(time(0));
return quick(nums,0,nums.size()-1,nums.size()-k);
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
return sortList(head,nullptr);
}
ListNode* sortList(ListNode*head,ListNode* tail)
{
if(head==nullptr)
{
return head;
}
if(head->next==tail)
{
head->next=nullptr;
return head;
}
ListNode*slow=head,*fast=head;
while(fast!=tail)
{
slow=slow->next;
fast=fast->next;
if(fast!=tail)
{
fast=fast->next;
}
}
ListNode* mid=slow;
return merge(sortList(head,mid),sortList(mid,tail));
}
ListNode *merge(ListNode*head1,ListNode* head2)
{
ListNode*dummyhead=new ListNode(0);
ListNode*temp=dummyhead,*temp1=head1,*temp2=head2;
while(temp1!=nullptr&&temp2!=nullptr)
{
if(temp1->val<temp2->val)
{
temp->next=temp1;
temp1=temp1->next;
}
else
{
temp->next=temp2;
temp2=temp2->next;
}
temp=temp->next;
}
if(temp1!=nullptr)
{
temp->next=temp1;
}
else if(temp2!=nullptr)
{
temp->next=temp2;
}
return dummyhead->next;
}
};