Posted on 2014-01-11 02:57
Uriel 阅读(103)
评论(0) 编辑 收藏 引用 所属分类:
LeetCode
给定一串数字,求最长的连续数字数目
map的应用?都忘记了map了...看了解题报告算式复习一下?
1 class Solution {
2 public:
3 int longestConsecutive(vector<int> &num) {
4 map<int, int> mp;
5 mp.clear();
6 int n = num.size();
7 for(int i = 0; i < n; ++i) {
8 mp.insert(pair<int, int>(num[i], 1));
9 }
10 int mx = 1, pre_k = 0, pre_v = 0;
11 map<int, int>::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 };