Tuesday, April 26, 2022

Leet Code 128. Longest Consecutive Sequence

 https://leetcode.com/problems/longest-consecutive-sequence/description/


Example 1:

Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.


  • sab number ko HashSet me add kr denge, fir har number ki min aur max range nikalenge.


package pep.Day68;

import java.util.HashSet;

public class LeetCode_128_Longest_Consecutive_Sequence {
public static void main(String[] args) {
System.out.println(longestConsecutive(new int[]{100, 4, 3, 200, 2, 1, 0}));
}

public static int longestConsecutive(int[] nums) {
HashSet<Integer> hs = new HashSet<>();
for (int i : nums)
hs.add(i);

int range = 0;
for (int i : nums) {
int min = i, max = i;

if (hs.contains(i)) {
while (hs.contains(min - 1)) {
min = min - 1;
hs.remove(min);
}

while (hs.contains(max + 1)) {
max = max + 1;
hs.remove(max);
}

range = Math.max(range, max - min + 1);
}
}

return range;
}
}

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...