《程序员代码面试指南》第八章 数组和矩阵问题 未排序数组中累加和为给定值的最长子数组系列问题

题目

未排序数组中累加和为给定值的最长子数组系列问题

java代码

package com.lizhouwei.chapter8;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author: lizhouwei
 * @CreateDate: 2018/5/7 21:57
 * @Modify by:
 * @ModifyDate:
*/
public class Chapter8_11 {
    public int getMaxLength(int[] arr, int k) {
        if (arr == null) {
            return 0;
        }
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);
        int sum = 0;
        int maxLen = 0;
        for (int i = 0; i < arr.length; i++) {
            sum = sum + arr[i];
            if (map.containsKey(sum - k)) {
                maxLen = Math.max(maxLen, i - map.get(sum - k));
            }
            map.put(sum, i);
        }
        return maxLen;
    }

    //测试
    public static void main(String[] args) {
        Chapter8_11 chapter = new Chapter8_11();
        int[] arr = {1, 2, 1, 1, 1};
        System.out.print("数组 arr = {1, 2, 1, 1, 1}中和为3的最长子数组长度为:");
        int maxLen= chapter.getMaxLength(arr, 3);
        System.out.print(maxLen);
    }
}

结果

posted @ 2018-05-07 21:59  lizhouwei  阅读(108)  评论(0编辑  收藏  举报