가장 긴 연속 시퀀스
                                            
                                                
                                                
                                                
                                                
                                                
                                                 5136 단어  javaleetcodealgorithms
                    
목적:
정수 nums의 정렬되지 않은 배열이 주어지면 가장 긴 연속 요소 시퀀스의 길이를 반환합니다.
O(n) 시간에 실행되는 알고리즘을 작성해야 합니다.
패턴: 배열 및 해싱
접근하다:
빅오 표기법:
시간 복잡도: O(n)
각 요소에 대해 n번 반복합니다.
공간 복잡도: O(n)
Set 데이터 구조를 사용하여 n개의 요소를 저장합니다.
암호:
class Solution {
    public int longestConsecutive(int[] nums) {
        // use hashset to store n values
        Set <Integer> hashSet = new HashSet<>();
        // maxLength to keep track of longest consecutive sequence 
        int maxLength = Integer.MIN_VALUE;
        // edge case 
        if (nums.length == 0 || nums.length == 1){
            return nums.length;
        }
        // add all elements into hashset 
        for(int i : nums){
            hashSet.add(i);
        }
        // get the first sequence 
        for(int curr : nums){
            // does left exist in hashMap
            // if it does not then it is the start of a sequence 
            if(!hashSet.contains(curr - 1)){
                int count = 1; 
                boolean flag = true;
                while(flag == true){
                    if(hashSet.contains(curr + 1)){
                        count++;
                        curr++;
                    } else {
                        flag = false;
                    }
                    maxLength = Math.max(maxLength, count);
                }
            }
        }
        return maxLength;
    }
}
Reference
이 문제에 관하여(가장 긴 연속 시퀀스), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/tammyvocs/longest-consecutive-sequence-234i텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)