Created
October 28, 2018 23:58
-
-
Save dmnugent80/2abc1c5f7a5bce9e4f9c04e4b013e93c to your computer and use it in GitHub Desktop.
Longest Consecutive Integers in a list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int longestConsecutive(int[] nums) { | |
if (nums.length == 0) return 0; | |
Set<Integer> numSet = new HashSet<>(); | |
for (int num : nums) { | |
numSet.add(num); | |
} | |
int maxCon = Integer.MIN_VALUE; | |
for (int i = 0; i < nums.length; i++) { | |
if (!numSet.contains(nums[i] - 1)) { | |
int currCon = 1; | |
int currentNum = nums[i]; | |
while (numSet.contains(currentNum + 1)) { | |
currentNum++; | |
currCon++; | |
} | |
maxCon = Math.max(currCon, maxCon); | |
} | |
} | |
return maxCon; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment