这是一道哈希表的题,非常巧的想法,去看x-1是否存在来判断是不是开头。

    1. class Solution {
    2. public:
    3. int longestConsecutive(vector<int>& nums) {
    4. set<int> aSet;
    5. for(auto x: nums)
    6. {
    7. if(aSet.find(x) == aSet.end())
    8. aSet.insert(x);
    9. }
    10. int iLen = 0;
    11. int iRes = 0;
    12. for(auto x: aSet)
    13. {
    14. if(aSet.find(x - 1) != aSet.end()) continue;
    15. int len = 0;
    16. for(int i = x; aSet.find(i) != aSet.end() ;i++)
    17. {
    18. len++;
    19. }
    20. iRes = max(iRes, len);
    21. }
    22. return iRes;
    23. }
    24. };