package daily20210106;
import java.util.HashMap;
import java.util.Map;
/**
* @author : zhaoliang
* @program :newCoder
* @description : 最长连续序列
* @create : 2021/01/06 19:42
*/
public class longestConsecutive {
//给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
public int longestConsecutive(int[] nums){
Map<Integer,Integer> map = new HashMap<>();
for (int num:nums
) {
map.put(num,1);
}
for (int num:nums
) {
forword(map,num);
}
return maxCount(map);
}
private int maxCount(Map<Integer, Integer> map) {
int max =0;
for (int num:map.keySet()
) {
max = Math.max(max,map.get(num));
}
return max;
}
private int forword(Map<Integer, Integer> map, int num) {
if (!map.containsKey(num)){
return 0;
}
int cnt = map.get(num);
if (cnt >1)return cnt;
cnt = forword(map,num+1)+1;
map.put(num,cnt);
return cnt;
}
}
最长连续序列
最新推荐文章于 2024-07-24 20:44:05 发布