[LeetCode]Longest Consecutive Sequence-2014.01.09
Posted on 2014-01-11 02:57 Uriel 閱讀(115) 評論(0) 編輯 收藏 引用 所屬分類: LeetCode給定一串數字,求最長的連續數字數目
map的應用?都忘記了map了...看了解題報告算式復習一下?
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 };
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 };