Uriel's Corner

Research Associate @ Harvard University / Research Interests: Computer Vision, Biomedical Image Analysis, Machine Learning
posts - 0, comments - 50, trackbacks - 0, articles - 594

[LeetCode]Longest Consecutive Sequence-2014.01.09

Posted on 2014-01-11 02:57 Uriel 阅读(98) 评论(0)  编辑 收藏 引用 所属分类: LeetCode
给定一串数字,求最长的连续数字数目
map的应用?都忘记了map了...看了解题报告算式复习一下?

 1 class Solution {
 2 public:
 3     int longestConsecutive(vector<int> &num) {
 4         map<intint> mp;
 5         mp.clear();
 6         int n = num.size();
 7         for(int i = 0; i < n; ++i) {
 8             mp.insert(pair<intint>(num[i], 1));
 9         }
10         int mx = 1, pre_k = 0, pre_v = 0;
11         map<intint>::iterator it;
12         for(it = mp.begin(); it != mp.end(); ++it) {
13             if(it == mp.begin()) {
14                 pre_k = it->first;
15                 pre_v = it->second;
16                 continue;
17             }
18             if(it->first == pre_k + 1) {
19                 it->second = pre_v + 1;
20                 mx = max(mx, it->second);
21             }
22             pre_k = it->first;
23             pre_v = it->second;
24         }
25         return mx;
26     }
27 };

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理