[LeetCode]Subarray Sum Equals K

来源:互联网 发布:java输入char字符串 编辑:程序博客网 时间:2024/06/05 05:15
  • Total Accepted: 7118
  • Total Submissions: 17265
  • Difficulty: Medium
  • Contributors:love_Fawn

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 = 2Output: 2

Note:

  1. The length of the array is in range [1, 20,000].
  2. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

方法一:(o(n**2)枚举)

public class Solution { public int subarraySum(int[] nums, int k) {   if(nums.length==0) return 0;        int re=0;        for(int i=0;i<nums.length;i++){            int sum=0;            for(int j=i;j<nums.length;j++){                sum+=nums[j];                if(sum==k) re++;            }        }        return re;     }}
方法二:(o(n))

其实和two Sum的道理是一模一样的,只是这题先得到累加数组,然后转化为数组中两个数之差等于定值k的数值对的个数,用Hash即可

public class Solution2 {public int subarraySum(int[] nums, int k) {if(nums.length==0) return 0;HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();int re=0;int sum=0;map.put(0, 1);for(int i=0;i<nums.length;i++){sum+=nums[i];if(map.containsKey(sum-k)){re+=map.get(sum-k);}Integer num=map.get(sum);if(num==null) num=0;map.put(sum,num+1);}return re;}}