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

    题目

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

    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);
        }
    }
    
    

    结果

  • 相关阅读:
    error :expected initializer before
    数字转字符
    转载转载转载指针占几个字节
    转载转载转载
    二维数组1
    响应式布局
    flex布局
    wepy踩坑经历
    css命名规范(转载)
    28.设计模式
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/9005242.html
Copyright © 2011-2022 走看看