[Programmer Code Interview Guide] recursion and dynamic programming - the longest continuous sequence array

topic

Given the array without arr, reflector length of the longest contiguous sequence.
Example Sub: arr = [100,4,200,1,3,2], is the longest contiguous sequence [1,2,3,4], 4 to return.

answer

Act one: sorting, re-iterate to find. The time complexity of O (nlogn), the spatial complexity of O (n)
Method Two:

  • With the map, the representative key traversed the length of a number, the longest contiguous sequence number value representative of the key is located.
  • Traversal arr, not only deal appeared.
  • Traversal key, map plus (key, 1), find key + 1, key-1, represents the connection of successive segments. Then the key head and tail only updated value contiguous sequence value, as continuous elements around the middle of the sequence elements have been added to both sides over the map it will not be over processed.
  • Time complexity of O (n), the spatial complexity of O (n).

Code (Act II)

import java.util.HashMap;

public class Main {
    public static void main(String args[]) {
        int[] arr= {100,4,200,1,3,2};
        System.out.println(longestContinueSeqLen(arr));
    }
    
    public static int longestContinueSeqLen(int[] arr){
        if(arr==null||arr.length==0) {
            return 0;
        }
        HashMap<Integer,Integer> map=new HashMap<>();
        int maxLen=Integer.MIN_VALUE;
        for(int num:arr) {
            if(!map.containsKey(num)) {
                map.put(num, 1);
                int endKey=num;
                if(map.containsKey(num+1)) {
                    int len=map.get(num+1);
                    endKey=num+len;
                    int newLen=len+1;
                    map.put(endKey, newLen);
                    map.put(num, newLen);
                    maxLen=maxLen>newLen?maxLen:newLen;
                }
                if(map.containsKey(num-1)) {
                    int len=map.get(num-1);
                    int begKey=num-len+1;
                    int newLen=len+map.get(num);
                    map.put(begKey, newLen);
                    map.put(endKey,newLen);
                    maxLen=maxLen>newLen?maxLen:newLen;
                }
            }
        }
        return maxLen;
    }
}

Guess you like

Origin www.cnblogs.com/coding-gaga/p/11072293.html