Leetcode中的错误列表

总结下自己遇到的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类型,小心减法造成溢出!



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值