一个无序正整数数组,求数组中最长连续序列的长度,时间复杂度越简单越好示例Input: [100, 4, 200, 5, 3, 2] 无序整数数组Output: 4 (最长连续序列[2, 3, 4, 5]的长度)
/**
* *****************************************************
* Copyright (C) 2020 bytedance.com. All Rights Reserved
* This file is part of bytedance EA project.
* Unauthorized copy of this file, via any medium is strictly prohibited.
* Proprietary and Confidential.
* ****************************************************
**/
package com.bytedance.p2pshopsystemservice.product;
import java.util.HashMap;
/**
* Test
*
* @author maoyong
* @date 04/16/2020 20:12
*/
public class TestMahon {
public int longestConsecutive(int[] nums) {
int max =0;
HashMap map =new HashMap();
for(int i: nums){
//判断是否存在,解决存在重复数据问题
if(map.getOrDefault(i,0)==0){
int left = map.getOrDefault(i-1,0);
int right = map.getOrDefault(i+1,0);
//临时最大sum数据 左边+右边+1 就算左/右为0不影响
int tempCount =1+left+right;
//每次更新,左 中 右的 sum数据
map.put(i,tempCount);
if(left!=0){
map.put(i-left,tempCount);
}
if(right !=0){
map.put(i+right,tempCount);
}
max = Math.max(max,tempCount);
}
}
return max;
}
public static void main(String[] args) {
TestMahon t =new TestMahon();
//100, 4, 200, 5, 3, 2
int[] nums =new int[]{100, 4, 200, 5, 3, 2};
System.out.println(t.longestConsecutive(nums));
}
}
网友评论