- 128. Longest Consecutive Sequenc
- 128. Longest Consecutive Sequenc
- 128. Longest Consecutive Sequenc
- 128. Longest Consecutive Sequenc
- 128. Longest Consecutive Sequenc
- 128. Longest Consecutive Sequenc
- 128. Longest Consecutive Sequenc
- 128. Longest Consecutive Sequenc
- 每天(?)一道Leetcode(17) Longest Cons
- Longest Consecutive Sequence
竟然是hard, 解法是比较巧妙但很好理解,没有复杂算法
class Solution {
public int longestConsecutive(int[] nums) {
if (nums == null || nums.length == 0){
return 0;
}
Set<Integer> set = new HashSet<>();
for (int num : nums){
set.add(num);
}
//[100,4,200,1,3,2]
//longest = 0
//num : 100
//down = 99
//up = 101
int longest = 0;
for (int i = 0; i < nums.length; i++){
int down = nums[i] - 1;
while (set.contains(down)){
set.remove(down);
down--;
}
int up = nums[i] + 1;
while (set.contains(up)){
set.remove(up);
up++;
}
//actually up - 1 - (down + 1) + 1
longest = Math.max(longest, up - down - 1);
}
return longest;
}
}
网友评论