# LeetCode-128. Longest Consecutive Sequence

        for (int num : num_set) {
int currentNum = num;
int currentStreak = 1;
while (num_set.contains(currentNum+1)) {
currentNum += 1;
currentStreak += 1;
}

longestStreak = Math.max(longestStreak, currentStreak);
}

class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> num_set = new HashSet<Integer>();
for (int num : nums) {
}

int longestStreak = 0;

for (int num : num_set) {
if (num_set.contains(num - 1)) {//优化
continue;
}
int currentNum = num;
int currentStreak = 1;

while (num_set.contains(currentNum + 1)) {
currentNum += 1;
currentStreak += 1;
}

longestStreak = Math.max(longestStreak, currentStreak);
}
return longestStreak;
}
}

class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> num_set = new HashSet<Integer>();
for (int num : nums) {
}

int longestStreak = 0;

for (int num : nums) {
if(!num_set.contains(num)){//如果num_set已不存在此元素，说明计算过，直接跳出
continue;
}
int currentStreak=1;//记录本次找到序列的长度
int downNum=num-1;
while(num_set.contains(downNum)){//依次查找小于他的数
currentStreak++;
num_set.remove(downNum);
downNum--;
}

int upNum=num+1;
while(num_set.contains(upNum)){//依次查找大于他的数
currentStreak++;
num_set.remove(upNum);
upNum++;
}

longestStreak = Math.max(longestStreak, currentStreak);
}
return longestStreak;
}
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120