#未排序数组中累加和为给定值的最长子数组系列问题补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;
    }


}

全部评论

相关推荐

争当牛马还争不上
码农索隆:1.把简历改哈 2.猛投,狠投 3.把基础打牢 这样你在有机会的时候,才能抓住
点赞 评论 收藏
分享
后来123321:别着急,我学院本大二,投了1100份,两个面试,其中一个还是我去线下招聘会投的简历,有时候这东西也得看运气
无实习如何秋招上岸
点赞 评论 收藏
分享
07-02 10:44
门头沟学院 C++
码农索隆:太实诚了,告诉hr,你能实习至少6个月
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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