Leetcode- 最長連續序列

128. 最長連續序列

解題思路:

/**
     * 1、通過PriorityQueue對數組先進行從小到大排序,但是要剔除重複的數組
     * 2、
     *   2.1: 然後出隊,定義臨時變量、臨時長度、已經最終的最大長度
     *   2.2: 如果當前出隊的值等於temp+1,則tempLength++,temp=currentValue
     *   2.2: 如果當前出隊的值不等於temp+1,則maxLength= 當前maxLength跟tempLength的最大值,並且temp=currentValue、tempLength = 1;
     *   2.3: 最後返回的時候,必須取maxLength跟tempLength的最大值
     * */

 

package com.cn.dl.leetcode;

import java.util.*;

/**
 * Created by yanshao on 2020-02-18.
 */
public class LongestConsecutive {
    /**
     * 1、通過PriorityQueue對數組先進行從小到大排序,但是要剔除重複的數組
     * 2、
     *   2.1: 然後出隊,定義臨時變量、臨時長度、已經最終的最大長度
     *   2.2: 如果當前出隊的值等於temp+1,則tempLength++,temp=currentValue
     *   2.2: 如果當前出隊的值不等於temp+1,則maxLength= 當前maxLength跟tempLength的最大值,並且temp=currentValue、tempLength = 1;
     *   2.3: 最後返回的時候,必須取maxLength跟tempLength的最大值
     * */
    public static int longestConsecutive(int[] nums) {
        if(nums == null || nums.length == 0){
            return 0;
        }
        //實現最大堆
        Queue<Integer> maxQueue = new PriorityQueue<>(nums.length, Comparator.comparingInt(o -> o));
        Map<Integer,Integer> existMap = new HashMap<>();

        for(int num : nums){
            if(existMap.containsKey(num)){
                continue;
            }
            existMap.put(num,num);
            maxQueue.add(num);
        }

        int maxLength = 1;
        int temp = maxQueue.poll();
        int tempLength = 1;
        while (! maxQueue.isEmpty()){
            int currentValue = maxQueue.poll();
            if(currentValue == temp + 1){
                tempLength ++;
                temp = currentValue;
            }else {
                maxLength = Math.max(maxLength,tempLength);
                tempLength = 1;
                temp = currentValue;
            }
        }
        return Math.max(maxLength,tempLength);
    }

    public static void main(String[] args) {
        int[] nums = new int[]{9,1,4,7,3,-1,0,5,8,-1,6};
        System.out.println(longestConsecutive(nums));
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章