class Solution {
public int longestConsecutive(int[] nums) {
if (nums.length < 1) {
return 0;
}
Arrays.sort(nums);
int longest = 1;
int curLong = 1;
int prev = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] == prev + 1) {
curLong++;
} else if (nums[i] > prev + 1 || nums[i] < prev) {
curLong = 1;
}
prev = nums[i];
if (curLong >= longest) {
longest = curLong;
}
}
return longest;
}
}
Runtime: 2 ms, faster than 99.51% of Java online submissions for Longest Consecutive Sequence.
Memory Usage: 39.1 MB, less than 73.81% of Java online submissions for Longest Consecutive Sequence.
내사랑 sort...^^
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> num_set = new HashSet<Integer>();
for (int num : nums) {
num_set.add(num);
}
int longestStreak = 0;
for (int num : num_set) {
if (!num_set.contains(num-1)) {
int currentNum = num;
int currentStreak = 1;
while (num_set.contains(currentNum+1)) {
currentNum += 1;
currentStreak += 1;
}
longestStreak = Math.max(longestStreak, currentStreak);
}
}
return longestStreak;
}
}
Runtime: 3 ms, faster than 86.59% of Java online submissions for Longest Consecutive Sequence.
Memory Usage: 39.3 MB, less than 63.48% of Java online submissions for Longest Consecutive Sequence.
루션이
내사랑 쉬셋이 사용