• LeetCode——Longest Consecutive Sequence


    Longest Consecutive Sequence

    补充一些map的使用方法

    begin,end,rbegin,rend。empty,clear,size。max_size 八个经常使用的函数.

    map.begin(); 是map的起始位置

    map.end(); 是指map的尾部,没有实际元素.

    map.find(); 查找函数

    map.rebgin()和.rend()是反向遍历数据的起始位置和终止位置

    map.empty() 推断map是否为空

    map.clear() 清空map

    map.size() 返回元素的数目

    map.max_size() 仅仅是一个容器的大小限定。
    决于 key Value所占字节比較大的一个。然后用4个字节的数字(unsigned_int_max=40亿左右) 除以2除以 所占字节就是这个值了。

    另外:

    unordered_map 的元素不以键值或映射的元素作不论什么特定的顺序排序
    unordered_map 容器比map容器更快地通过键值訪问他们的单个元素

    插入:

    插入有三种方式,第一种:insert(pair

    iterator:

    map<int,string> _map;
    map<int,string>::iterator iter;
    for(iter = _map.begin() ; iter != _map.end() ; ++iter)
    {
      cout<<iter->first<<" "<<iter->second<<endl;
    }

    题解 Longest Consecutive Sequence

    题目:

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
    For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
    Your algorithm should run in O(n) complexity.

    思路:

    用一个哈希表 unordered_map

    C++代码:

    #include <iostream>
    #include <vector>
    #include <unordered_map>
    
    using namespace std;
    
    class Solution{
        public:
            int longestConsecutive(const vector<int> &num) {
                unordered_map<int, bool> used;
    
                for (int i:num) used[i] = false;
    
                int longest = 0;
    
                for (int i:num) {
                    if (used[i]) continue; //结束本次循环
    
                    int length = 1;
    
                    used[i] = true;
    
                    for (int j = i+1; used.find(j)!=used.end(); ++j){
                        used[j] = true;
                        ++length;
                    }
    
                    for (int j = i-1; used.find(j)!=used.end(); --j){
                        used[j] = true;
                        ++length;
                    }
                    longest = max(longest, length);
                }
                return longest;
            }
    };
    
    int main(int argc, char *argv[]) {
        int arr[] = {100,4,200,1,3,2};
        vector<int> vec(&arr[0],&arr[6]);
        Solution s;
        int result = s.longestConsecutive(vec);
        printf("%d",result);
    }
  • 相关阅读:
    asp.net AD 域验证
    ASP.NET身份验证
    .Net默认IE版本号的两种方式
    (转)移动端自适应方案
    (转)手机web——自适应网页设计(html/css控制)
    (转)优雅降级和渐进增强的区别
    (转)hasLayout与BFC的触发条件
    (转)js中几种实用的跨域方法原理详解
    (转)js实现继承的5种方式
    (转)js 判断各种数据类型
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/5275888.html
Copyright © 2020-2023  润新知