慢慢把在leetcode上写的代码搬过来(不知道leetcode是啥的童鞋请点击http://leetcode.com/),由于对于题目的理解或者coding技巧随时变化,所以,这一系列的博客可能会被老是修改 = =!增删都会比较频繁,见谅。另外题目分类本来就很难,排除掉我漏分错分的情况,很多题目本身就属于几个类别(比如可能它在排序类,又在递归类,还在查找类等等等等),所以一个你觉得是A类的,在A类里面没有找到的话~可以试试其他。
Merge k Sorted Lists:
题目描述很简单:Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
也是很经典的题了,一般都是用一个大小为K的最小堆来维护,时空复杂度O(nlogk)+O(k) (空间复杂度我一般去掉输入输出必须的空间,因为这部分空间无论你怎么优化都没法避免的)。
code:
//优先队列的使用
class Solution {
public:
struct cmp{
bool operator() (ListNode* x,ListNode* y){
return x->val>y->val; //最小堆
}
};
ListNode *mergeKLists(vector &lists) {
priority_queue,cmp> pq;
ListNode* head = NULL,**headP = &head;
for(int i=0;inext) pq.push(tmp->next);
*headP = tmp;
headP = &((*headP)->next);
}
*headP = NULL;
return head;
}
};
堆就用C++的priority_queue实现,注意我代码里面用了个二维指针,为啥要用它,实际上它的作用跟dummy head是一样的,就是新开一个节点指向头,避免头指针特判的情况。
Merge Two Sorted Lists:
题目描述:Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
这个题是上面那个题的简化版,由于只有两个list,就不需要用堆来维护了。
code:
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode* dummy = new ListNode(1),*ite = dummy;
while(l1&&l2){
if(l1->valval){
ite->next = l1;
l1=l1->next;
}else{
ite->next = l2;
l2=l2->next;
}
ite=ite->next;
}
l1 = l2?l2:l1;
while(l1){
ite->next=l1;
l1=l1->next;
ite=ite->next;
}
ite->next = NULL;
ite = dummy->next;
delete dummy;
return ite;
}
};
由于有是链表的题,还是有链表头特判的问题。这次我用的是dummy head(而不是指针的指针),可以比较一下差别。
Merge Sorted Array:
题目描述:Given two sorted integer arrays A and B, merge B into A as one sorted array.
跟上面的大同小异,指针换成数组了。
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int end = n+m-1;
int ia=m-1,ib=n-1;
while(ia>=0&&ib>=0)
{
if(A[ia]>B[ib])
A[end--] = A[ia--];
else
A[end--] = B[ib--];
}
while(ia>=0)
A[end--] = A[ia--];
while(ib>=0)
A[end--] = B[ib--];
}
};