题目传送: https://leetcode.cn/problems/longest-consecutive-sequence/submissions/
运行效率:
代码如下:
public int longestConsecutive(int[] nums) {
//处理边界情况
if(nums.length==0){
return 0;
}
Arrays.sort(nums);
int result = 1;
int left = 0;
int right = 0;
while (right < nums.length - 1) {
//如果是连续的,那就右指针一直往后移动
if (nums[right]== nums[right + 1] ||nums[right] + 1 == nums[right + 1]) {
right++;
//如果已经移动到数组的边界了
if(right==nums.length-1){
int length = getLength(nums, left, right);
result = Math.max(length, result);
}
}else{
int length = getLength(nums, left, right);
result = Math.max(length, result);
left=right+1;
right=left;
}
}
return result;
}
/**
* 查询left到right位置之间所有不重复元素的个数
* @param nums
* @param left
* @param right
* @return
*/
public int getLength(int[] nums,int left,int right){
HashSet<Integer> set = new HashSet<>();
for(int i=left;i<=right;i++){
set.add(nums[i]);
}
return set.size();
}