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

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

https://www.nowcoder.com/practice/ab190c44af0141d58037c3f95109d722

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        int[] arr = new int[N];
        for (int i = 0; i < N; i++) {
            arr[i] = in.nextInt();
        }
        int len = getLength(arr);
        System.out.print(len);
    }

    private static int getLength(int[] arr) {
        if (arr == null) {
            return 0;
        }
        int N = arr.length;
        //key 正数个数与负数个数的差值, value index
        Map<Integer,Integer> map = new HashMap<>();
        map.put(0,-1);


        int Z = 0,F = 0;//1的个数,0的个数
        int res = 0;
        for (int i = 0; i < N; i++) {
            Z += arr[i] == 1 ? 1 : 0;
            F += arr[i] == 0 ? 1 : 0;
            int cha = Z - F;
            if (map.containsKey(cha)) {
                res = Math.max(res, i - map.get(cha));
            }else {
                map.put(cha,i);
            }
        }
        return res;
    }
}

全部评论

相关推荐

05-20 13:59
门头沟学院 Java
米黑子米黑子:你这个成绩不争取下保研?
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-11 11:24
大家还是用ai改吧,我心疼得要死,就当花钱买教训吧,人家直接拿完钱就跑路了
程序员小白条:简历修改700....神奇,又不是帮你面试,咋的,简历修改从双非变92了还是没实习变成有大厂实习了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务