Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Created October 28, 2018 23:58
Show Gist options
  • Save dmnugent80/2abc1c5f7a5bce9e4f9c04e4b013e93c to your computer and use it in GitHub Desktop.
Save dmnugent80/2abc1c5f7a5bce9e4f9c04e4b013e93c to your computer and use it in GitHub Desktop.
Longest Consecutive Integers in a list
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