• 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.

    Example 1:

    Input:nums = [1,1,1], k = 2
    Output: 2
    

    Constraints:

    • The length of the array is in range [1, 20,000].
    • The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
    class Solution {
        public int subarraySum(int[] nums, int k) {
            int count = 0;
            for(int start = 0; start < nums.length; start++){
                int sum = 0;
                for(int end = start; end < nums.length; end++){
                    sum += nums[end];
                    if(sum == k) count++;
                }
            }
            return count;
        }
    }

     本来想在内循环添加个break(在sum ==k后)后来发现不对,是因为如果是纯0的话会有这个问题,好贱呐

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

    https://leetcode.com/problems/subarray-sum-equals-k/discuss/102106/Java-Solution-PreSum-%2B-HashMap

    The idea behind this approach is as follows: If the cumulative sum(repreesnted by sum[i]sum[i] for sum upto i^{th}ith index) upto two indices is the same, the sum of the elements lying in between those indices is zero. Extending the same thought further, if the cumulative sum upto two indices, say ii and jj is at a difference of kk i.e. if sum[i] - sum[j] = ksum[i]sum[j]=k, the sum of elements lying between indices ii and jj is kk.

    Based on these thoughts, we make use of a hashmap mapmap which is used to store the cumulative sum upto all the indices possible along with the number of times the same sum occurs. We store the data in the form: (sum_i, no. of occurences of sum_i)(sumi,no.ofoccurencesofsumi). We traverse over the array numsnums and keep on finding the cumulative sum. Every time we encounter a new sum, we make a new entry in the hashmap corresponding to that sum. If the same sum occurs again, we increment the count corresponding to that sum in the hashmap. Further, for every sum encountered, we also determine the number of times the sum sum-ksumk has occured already, since it will determine the number of times a subarray with sum kk has occured upto the current index. We increment the countcount by the same amount.

    After the complete array has been traversed, the countcount gives the required result.

    妙哉

    map.put(0, 1),如果遇到第一个index有map.get(sum - k == 0), 说明从0到index的sum == k

  • 相关阅读:
    PE 合并节
    VirtualAddress与VirtualSize与SizeOfRawData与PointerToRawData的关系
    .net core publish 找不到视图
    c++ rc 文件内包含中文字符导致在unicod环境下编译乱码
    .net 5.0 ref文件夹的作用
    .net 5.0项目升级工具
    HttpWebRequest DNS缓存清理
    .net 5.0 发布命令总结
    关于dll not found 排查解决
    关于win7 无法识别sha256签名导致驱动无法安装的问题
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13155839.html
Copyright © 2020-2023  润新知