Two Solution: O(n^2)O(1) & O(n)O(n)


  • 0

    need to consider negative numbers and duplicated sums(e.x. [0,0,0] 0 -> 6)

    public class Solution {
        public int subarraySum(int[] nums, int k) {
            if (nums == null || nums.length == 0) return 0;
            int res = 0;
            int sum = 0;
            int n = nums.length;
            for (int i = 0; i < n; i++) {
                sum = nums[i];
                if (sum == k) res++;
                for (int j = i + 1; j < n; j++) {
                    sum += nums[j];
                    if (sum == k) res++;
                }
            }
            return res;
        }
    }
    
    public class Solution {
        public int subarraySum(int[] nums, int k) {
            if (nums == null || nums.length == 0) return 0;
            int res = 0; 
            int n = nums.length;
            int sum = 0;
            Map<Integer, Integer> map = new HashMap<>();
            map.put(0, 1);
            for (int i = 0; i < n; i++) {
                sum += nums[i];
                if (map.containsKey(sum - k)) {
                    res += map.get(sum - k);
                }
                map.put(sum, map.getOrDefault(sum, 0) + 1);
            }
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.