zoukankan      html  css  js  c++  java
  • 128. 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.

    空间换时间,用了 map.
    map 咋声明?判断 key = n 是否在该 map 中咋弄?

    map<int, int> map;
    if(map.find(n) == map.end()){} //若 key = n 不在map中
    

    本题关键点(思路很清晰):
    主要分 2 steps:

    扫描数组, n 表示当前扫到的元素.
    
    step1:
    	若 key = n 不在 map 中, 就找n的左(n-1)、右(n+1)邻居, 然后sum = left + right + 1,
    	再把 map[n] = sum;
    
    step2:
    	接着更新 这个连续序列的 边界(boundarys, boundarys, 重要的话说3遍!) 为 sum 值, 如:
    	e.g [1,2,3,4,5], A[1] = A[5] = 5, except A[2,..,4]!
    	若无 左 或 右 边界,则不受影响 respectively, 如下核心代码:
    	map[n - left] = sum;
    	map[n + right] = sum;
    
    key = n 在 map 中的话,跳过本次循环,因为重复了,不必理会了.
    

    人家想法,咱家代码:
    (O(n)) time, (O(n)) extra space.

    int longestConsecutive(vector<int>& A) {
    	int res = 0;
    	map<int, int> map;
    
    	for (int n : A) {
    		// 若 key = n 不在map中
    		if (map.find(n) == map.end()) {
    			// step 1: left, right issues
    			int left = (map.find(n - 1) != map.end()) ? map[n - 1] : 0;
    			int right = (map.find(n + 1) != map.end()) ? map[n + 1] : 0;
    			int sum = left + right + 1;
    			map[n] = sum;
    
    			res = max(res, sum);
    
    			// step 2: boundary(s) issues
    
    			// update the length of
    			// this consecutive sequence boundary(s)
    			// e.g [1,2,3,4,5], A[1] = A[5] = 5, except A[2,..,4]!
    			// 若无 左 或 右 边界,则不受影响 respectively.
    			map[n - left] = sum;
    			map[n + right] = sum;
    		} else {
    			// duplicates
    			continue;
    		}
    	}
    	return res;
    }
    

    还有牛人的超短的代码:
    https://leetcode.com/problems/longest-consecutive-sequence/discuss/

  • 相关阅读:
    团队冲刺-1
    最优惠购买书籍
    gogoing软件NABCD
    二维数组首尾相连
    首尾相连一维数组的最大子数组和
    二维数组返回最大子矩阵之和
    石家庄铁道大学基础教学楼电梯使用调查
    子数组最大值求和
    返回一个整数数组中最大子数组的和-课堂训练(子数组为连续)
    软件工程概论-四则运算
  • 原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7446219.html
Copyright © 2011-2022 走看看