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

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

https://www.nowcoder.com/practice/545544c060804eceaed0bb84fcd992fb

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


        int Z = 0,F = 0;//正数个数,负数个数
        int res = 0;
        for (int i = 0; i < N; i++) {
            if (arr[i] == 0) {
                //0 跳过,相当于取i之前的数
                continue;
            }
            Z += arr[i] > 0 ? 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;
    }


}

全部评论

相关推荐

06-08 22:25
门头沟学院 Java
从零开始的转码生活:这hr不会打开手机不分青红皂白给所有人群发这句话,过一会再给所有人再发一遍,这肯定会有重复的,不管,再过一会再发一遍
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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