1546. 和为目标值的最大数目不重叠非空子数组数目 LeetCode第201场周赛

1546. 和为目标值的最大数目不重叠非空子数组数目 LeetCode周赛

传送门

传送门

结题思路

思路1:用set存储前缀和,若加上nums[i]的和减去target的值存在set中,则数目加1,且clear set。
HashSet存储前缀和

class Solution {
    public int maxNonOverlapping(int[] nums, int target) {
        HashSet<Integer> s = new HashSet<Integer>();
        s.add(0);
        int sum = 0, count = 0;
        for(int i = 0; i < nums.length; i++)
        {
            sum += nums[i];
            if(s.contains(sum - target))
            {
                ++count;
                s.clear();
                sum = 0;
            }
            s.add(nums[i]);
        }
        return count;        
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40092110/article/details/108029037
今日推荐