SubArray + HashMap
Use hashmap to record count/index. Must init base case {0: -1} or {0: 1}
Subarray Sum Equal Zero
Given an integer array, find a subarray where the sum of numbers is zero. Your code should return the index of the first number and the index of the last number. Example Given [-3, 1, 2, -3, 4], return [0, 2] or [1, 3].
If we find that a running sum value at index j has been previously seen before in some earlier index i in the array, then we know that the sub-array (i,j] contains a desired sum
325. Maximum Size Subarray Sum Equals K
用hashmap 紀錄到當前idx每個idx的presum, 如果能找cur sum - previous sum == k update max
presum只需update第一次出現的地方
560 Subarray Sum Equals K
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Time O(n), Space O(n)
用hashmap 紀錄到當前idx每個idx的presum, 如果能找cur sum - previous sum == k update count
525. Contiguous Array
Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
參考subarray sum equal to k, k 改為0, 用sum, 1 遞增 0遞減, 只要count的number 曾經出現過代表上個index到當前index有相同數字的0,1 用一個hashmap紀錄count的index, 如果count在map裡就update max_len
523 Continuous Subarray Sum Equals To n*k
Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also an integer.
Time O(n^2), Space O(1)
Time O(n), Space O(n)
Loop over array. Use a hashamp to record the (residue, idx). If we can see the residue in map, means the sum of numbers between i and j satisfied multiple of k
437. Path Sum III
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
Last updated
Was this helpful?