Leetcode 1546 和为目标值的最大数目不重叠非空子数组数目 贪心前缀和

  JAVA:

public final int maxNonOverlapping(int[] nums, int target) {
        int re = 0;
        int point = 0;
        while (point < nums.length) {
            int sum = 0;
            Set<Integer> preSums = new HashSet<Integer>();
            preSums.add(0);
            while (point < nums.length) {
                sum += nums[point];
                preSums.add(sum);
                if (preSums.contains(sum - target)) {
                    re++;
                    break;
                } else {
                    point++;
                }
            }
            point++;
        }
        return re;
    }

  JS:

var maxNonOverlapping = function (nums, target) {
    let re = 0;
    let point = 0;
    while (point < nums.length) {
        let sums = new Set();
        sums.add(0);
        let sum = 0;
        while (point < nums.length) {
            sum += nums[point];
            if (sums.has(sum - target)) {
                re++;
                break;
            } else {
                sums.add(sum);
                point++;
            }
        }
        point++;
    }
    return re;
};

 

posted @ 2020-08-25 23:17  牛有肉  阅读(270)  评论(0编辑  收藏  举报