LeetCode OJ--Longest Consecutive Sequence ***
2014-01-15 16:41
447 查看
http://oj.leetcode.com/problems/longest-consecutive-sequence/
起初想的是排序,查了下O(n)的排序算法有计数排序、基数排序、桶排序。后来考虑到数据的范围不知道,并且还有可能是负数,这几种方法都不太适用。
之后想到了容器,Map、Set的查找是哈希查找,复杂度为O(1).
重点是思路的转换,以及 set 的应用。
起初想的是排序,查了下O(n)的排序算法有计数排序、基数排序、桶排序。后来考虑到数据的范围不知道,并且还有可能是负数,这几种方法都不太适用。
之后想到了容器,Map、Set的查找是哈希查找,复杂度为O(1).
#include <iostream> #include <vector> #include <unordered_set> using namespace std; class Solution { public: unordered_set<int> dict; int findLongestConsective(int num) { int ans = 0; int temp = num; //往上找 while(dict.find(temp)!=dict.end()) { ans++; dict.erase(temp); temp++; } //往下找 while(dict.find(num-1)!=dict.end()) { ans++; dict.erase(num-1); num--; } return ans; } int longestConsecutive(vector<int> &num) { for(int i = 0;i<num.size();i++) dict.insert(num[i]); int maxLen = 0; for(int i = 0;i<num.size();i++) { int t = findLongestConsective(num[i]); if(t>maxLen) maxLen = t; } return maxLen; } }; int main() { vector<int> num; num.push_back(100); num.push_back(4); num.push_back(200); num.push_back(1); num.push_back(3); num.push_back(2); Solution myS; int ans = myS.longestConsecutive(num); cout<<ans<<endl; }
重点是思路的转换,以及 set 的应用。
相关文章推荐
- LeetCode OJ——Single Number II
- LeetCode OJ——Text Justification
- LeetCode OJ——Remove Duplicates from Sorted List
- LeetCode OJ--Reverse Nodes in k-Group **
- LeetCode OJ:Evaluate Reverse Polish Notation
- LeetCode OJ:Word Break II
- LeetCode OJ:Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode OJ:Gray Code
- LeetCode OJ:Set Matrix Zeroes
- LeetCode OJ:Permutation Sequence
- LeetCode OJ:Jump Game II
- LeetCode OJ:Implement strStr()
- LeetCode OJ:Palindrome Number
- LeetCode OJ--Partition List
- LeetCode OJ --问题与解答 Roman to Integer
- 【LEETCODE OJ】Reorder List
- 【LeetCode OJ】Palindrome Partitioning
- 【LeetCode OJ】Binary Tree Maximum Path Sum
- LeetCode OJ - Max Points on a Line
- LeetCode OJ - Word Break