128. Longest Consecutive Sequence


做题历程:

  1. 2016/Oct/22 本次应该是第二次做,本次大致耗时20分钟,独立解出(但是看了提示)

本题在Hard里面算是难度较低的,不过第一次做的话很难想到是用Union Find,但是一旦想到后就不那么复杂了。

我认为我第一次解法更好(那次是看了答案)。。就说第一次的解法了。。毕竟能用one pass解出,所以正确性难以凭空想到,但是仔细思考10几秒,是能想通的。。

大体解法:

  1. 设定一个unordered_map<int, int>key是数组中的元素,value以该元素为起点或终点的(已知)序列长度
  2. 遍历nums,如果某元素不在hashmap中,它的值就是:1 + hashmap[nums[i]-1] + hashmap[nums[i]+1]
  3. 记得要更新该序列左右两端点为key的值

代码如下:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_map<int, int> hashmap;
        int res = 0;
        for (int i = 0; i < nums.size(); ++i) {
            if (hashmap.find(nums[i]) == hashmap.end()) {
                int left = hashmap.find(nums[i]-1) != hashmap.end() ? hashmap[nums[i]-1] : 0;
                int right =  hashmap.find(nums[i]+1) != hashmap.end() ? hashmap[nums[i]+1] : 0;
                int sum = left + right + 1;
                hashmap[nums[i]] = sum;
                res = max(sum, res);
                hashmap[nums[i]-left] = sum;
                hashmap[nums[i]+right] = sum;
            }
            else {
                continue;
            }
        }
        return res;
    }
};

results matching ""

    No results matching ""