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

题目

未排序正数数组中累加和为给定值的最长子数组长度

java代码

package com.lizhouwei.chapter8;

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

/**
 * @Description: 未排序正数数组中累加和为给定值的最长子数组长度
 * @Author: lizhouwei
 * @CreateDate: 2018/5/7 21:47
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter8_10 {

    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_10 chapter = new Chapter8_10();
        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);
    }
}

结果

原文地址:https://www.cnblogs.com/lizhouwei/p/9005229.html