• [LeetCode]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.

    class Solution {
    public:
          int longestConsecutive(const vector<int> &nums) {
            unordered_map<int, int> map;
            int result = 0;
            for (auto i: nums){
                if (map.find(i) = map.end()){
                int left = map.find(i - 1) != map.end() ? map[i - 1]: 0;
                int right = map.find(i + 1) != map.end() ? map[i + 1]: 0;
                int lenght = left + right + 1;
                map[i] = length;
                map[i - left] = length;
                map[i + right] = length;
                result = max(result, length);
                } 
            }
            return result; 
          }
    };
    

      

    class Solution {
    public:
          int longestConsecutive(const vector<int> &nums) {
            unordered_map<int, bool> map;
            for (auto i: nums) map[i] = false;
            int result = 0;
            for (auto i: nums){
                if (map[i]) continue;
                map[i] = true;
                int length = 1;
                for (int j = i + 1; map.find(j) != map.end(); j++){
                    map[j] = true;
                    length += 1;
                }
    
                for (int j = i - 1; map.find(j) != map.end(); j--){
                    map[j] = true;
                    length += 1;
                }
                result = max(result, length);
            }
            return result; 
          }
    };
    

      

  • 相关阅读:
    自定义拦截器
    MVP模式网络请求购物车
    mvp+RecyclerView实现网络请求
    二维码扫描
    进度条加载
    画圆移动
    简单排序
    批量发货
    Angular服务
    终极购物车
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/7675844.html
Copyright © 2020-2023  润新知