懒人读算法(四)-寻找最大连续值

来源:互联网 发布:国牌lolita淘宝店铺 编辑:程序博客网 时间:2024/06/15 12:30

趣味题

给一个没有排序的整数数组,寻找最大的连续值
如[100, 4, 200, 1, 3, 2] ,则最长的数组是[1, 2, 3, 4],返回值最大长度是4

答案:

public class Solution {    public int longestConsecutive(int[] nums) {        int res = 0;        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();        for(int n : nums) {//遍历            if(!map.containsKey(n)) {//map里不存在n                int left = (map.containsKey(n - 1)) ? map.get(n - 1) : 0;//左边的最大连续数值                int right = (map.containsKey(n + 1)) ? map.get(n + 1) : 0;//右边的最大连续值                int sum = left + right + 1;//最大连续值                map.put(n, sum);//当前值得最大连续值                res = Math.max(res, sum);                map.put(n - left, sum);//更新当前值最左边连续值的值为sum                map.put(n + right, sum);//更新最右边连续值为sum            }            //4    left =0 right =0  sum =1            //1    left=0 right=0 sum=1            //3    left=0 right=1 sum=2          map(4,2)            //2    left=1  right=2  sum=4       map(2,4),map(1,4),map(4,4)            else {                continue;            }        }        return res;    }}

核心思路:遍历整个数组,并把结果放在map里key里,value是当前值左边和右边的最大连续值数加1
再更新当前值得最左边和最右边的值为sum