128. Longest Consecutive Sequence

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_map<int, int> cLen(nums.size()); //consecutiveLen
        int res = 0;
        for (int x : nums)
            if (!cLen.count(x)) {
                int l = cLen.count(x - 1) ? cLen[x - 1] : 0;
                int r = cLen.count(x + 1) ? cLen[x + 1] : 0;
                int sum = l + r + 1;
                res = max(sum, res);
                cLen[x - l] = cLen[x + r] = cLen[x] = sum;
            }
        return res;
    }
};
public int longestConsecutive(int[] num) {
  int max = 0;

  Set<Integer> set = new HashSet<Integer>();
  for (int i = 0; i < nums.length; i++) {
    set.add(nums[i]);
  }

  for (int i = 0; i < nums.length; i++) {
    int count = 1;

    // look left
    int num = nums[i];
    while (set.contains(--num)) {
      count++;
      set.remove(num);
    }

    // look right
    num = nums[i];
    while (set.contains(++num)) {
      count++;
      set.remove(num);
    }

    max = Math.max(max, count);
  }

  return max;
}

results matching ""

    No results matching ""