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

    结果

  • 相关阅读:
    swift基础语法(05- 可选值)
    swift基础语法(03- 运算符)
    swift基础语法(04- 元组)
    swift基础语法(02-基本数据类型)
    tableView的全屏穿透效果的实现
    ScrollView属性解析
    TableView的重要性
    SQLite操作
    openFileOutput的几种文件模式
    保存文件到SDcard
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/9005229.html
Copyright © 2011-2022 走看看