Unsorted array subarray longest accumulation problem given value.

Problem Description: An array may comprise a positive, negative, and 0.5 to identify the length of the longest and the subarray k.

This topic has methods for solving violent:

Thoughts: We consider each node in the array as the tail node of a sub-array, and for that node, from the beginning to the node traversed to traverse position, it encounters the first node and the sum obtained subarray length ... this algorithm in fact, we need to iterate again, to calculate each node to the head node and the job.

Optimal Solution: use HashMap, the time complexity is O (n), the spatial complexity is O (n)

Ideas:

1, HashMap value of the node index, key is the head node and the node array.

2, again traversing the array, sum value of the head node for a node obtained, if there is a key equal to the HashMap sum - k, then the value taken is the index of the node, and then obtained by subtracting the length of the subarray .

3, the value of the sum determined in the Map nodes are not, if not, it is able to save the index value and the sum, if any, do not exist, because not the longest sub-arrays corresponding to

Key: Because it is possible to first element is the first node of the longest sub-array, so the first key is a 0 in the storage Map, value for the element -1

code show as below

package Array;

import java.util.HashMap;

public class LongestSubArrayEqualsSum2 {
    public static int longestSubArrayEqualsSum2(int[] array,int k){
        HashMap<Integer,Integer> map = new HashMap<>();
        int len = 0;//和为k的最长子数组长度
        int sum = 0;
        map.put(0,-1);
        for(int i = 0; i < array.length; i++){
            sum += array[i];
            if(map.containsKey(sum - k)){
                len = len > map.get(sum - k)?len:map.get(sum - k);
            }
            if(!map.containsKey(sum)){
                map.put(sum,i);
            }
        }
        return len;
    }
}

 

Guess you like

Origin blog.csdn.net/shen19960603/article/details/90901083