总结下自己遇到的leetcode错误(持续更新):
1. 忘记给返回返回值!
2. sort(v.begin(), b.end(), cmp)其中cmp如果是函数,则不能是成员函数!如leetcode中的merge intervals http://oj.leetcode.com/submissions/detail/5754868/
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
static bool comp(const Interval& i1,const Interval& i2){
if(i1.start!=i2.start)
return i1.start<i2.start;
else
return i1.end<i2.end;
}
vector<Interval> merge(vector<Interval> &intervals) {
if(intervals.size()==0 || intervals.size()==1) return intervals;
sort(intervals.begin(), intervals.end(), comp);
vector<Interval> new_intervals;
int start, end;
start=intervals[0].start;
end=intervals[0].end;
for(int i=1;i<intervals.size();i++){
if(intervals[i].start>end){
new_intervals.push_back(Interval(start,end));
start=intervals[i].start;
end=intervals[i].end;
}
else{
if(intervals[i].end>end)
end=intervals[i].end;
}
}
new_intervals.push_back(Interval(start,end));
return new_intervals;
}
};
3. 多重图的遍历,如何将多重边和重复返回区分开来,可以利用map来做,如leetcode中的clone graph http://oj.leetcode.com/problems/clone-graph/
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(node==NULL) return NULL;
map<int, UndirectedGraphNode *> visited;
return doCopyGraphNode(node,visited);
}
UndirectedGraphNode *doCopyGraphNode(UndirectedGraphNode *node, map<int, UndirectedGraphNode *>& visited){
UndirectedGraphNode* cnode=new UndirectedGraphNode(node->label);
visited[node->label]=cnode;
vector<UndirectedGraphNode *>::iterator it=(node->neighbors).begin();
for(;it!=(node->neighbors).end();it++){
if(visited.count((*it)->label)){
(cnode->neighbors).push_back(visited[(*it)->label]);
}
else{
UndirectedGraphNode* onode=doCopyGraphNode(*it,visited);
(cnode->neighbors).push_back(onode);
}
}
return cnode;
}
};
4. size_t是unsigned类型,小心减法造成溢出!