zoukankan      html  css  js  c++  java
  • 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);
    }
  • 相关阅读:
    如何在Oracle中复制表结构和表数据
    linux --备份oracle
    Jira-Clone与发邮件的使用
    C# lock关键词/lock语句块、线程锁
    HTML5实现简单圆周运动示例
    C#使用FFmpeg 将视频格式转换成Gif图片示例
    C#使用FFmpeg 将视频格式转换成MP4示例
    ffmpeg ffplay ffprobe资料整理
    Asp.Net MVC是否针对每次请求都重新创建一个控制器实例
    Asp.Net MVC--Controller激活2
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/5275888.html
Copyright © 2011-2022 走看看