From dbf2cd07ce97517c5f8c12d56b7e136ce19b2875 Mon Sep 17 00:00:00 2001 From: ashmichheda Date: Tue, 23 Feb 2021 14:57:25 -0700 Subject: [PATCH] added solution and test case for 128 --- .../java/com/fishercoder/solutions/_128.java | 24 +++++++++++++++++++ src/test/java/com/fishercoder/_128Test.java | 24 +++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 src/test/java/com/fishercoder/_128Test.java diff --git a/src/main/java/com/fishercoder/solutions/_128.java b/src/main/java/com/fishercoder/solutions/_128.java index f23cff3b54..1a7dda58b8 100644 --- a/src/main/java/com/fishercoder/solutions/_128.java +++ b/src/main/java/com/fishercoder/solutions/_128.java @@ -113,4 +113,28 @@ public int longestConsecutive(int[] nums) { return max; } } + + public static class Solution3 { + public int longestConsecutive(int[] nums) { + HashSet numSet = new HashSet<>(); + for (int num : nums) { + numSet.add(num); + } + + int longestStreak = 0; + for (int num : nums) { + if (!numSet.contains(num - 1)) { + int currentNum = num; + int currentStreak = 1; + + while (numSet.contains(currentNum + 1)) { + currentNum += 1; + currentStreak += 1; + } + longestStreak = Math.max(longestStreak, currentStreak); + } + } + return longestStreak; + } + } } diff --git a/src/test/java/com/fishercoder/_128Test.java b/src/test/java/com/fishercoder/_128Test.java new file mode 100644 index 0000000000..514e099b4a --- /dev/null +++ b/src/test/java/com/fishercoder/_128Test.java @@ -0,0 +1,24 @@ +package com.fishercoder; + +import com.fishercoder.solutions._128; +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class _128Test { + private static _128.Solution3 solution3; + private static int[] nums; + + @BeforeClass + public static void setup() { + solution3 = new _128.Solution3(); + } + + @Test + public void test1() { + nums = new int[]{100,4,200,1,3,2}; + int result = 4; + assertEquals(4, solution3.longestConsecutive(nums)); + } +}