Sum—LeetCode-560 Subarray Sum Equals K

来源:互联网 发布:标准篮球场数据 编辑:程序博客网 时间:2024/06/04 18:25

题目描述:

Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals tok.

Example 1:

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

Output: 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 integerk is [-1e7, 1e7].
思路一(递归解法):总共等于k的个数 = 以数组中第一个元素为首的连续和等于k个数 + 除了第一个元素外,剩余元素中连续和等于k的个数,代码参考:

public int subarraySum(int[] nums, int k) {        if(nums.length == 1 && nums[0] != k)            return 0;        return rescuSum(nums, k, 0);    }    private int rescuSum(int[] nums, int k, int start) {        if(start >= nums.length){            return 0;        }        int firstCount = 0;        int sum = 0;        for(int i = start; i < nums.length; ++i) {            sum += nums[i];            if(sum == k){                ++firstCount;            }        }        return firstCount + rescuSum(nums, k, start + 1);    }

思路二(没有想到,hash映射)遍历所有起点是最开始元素的子序列,起名叫sum[i],只要两个sum[i]的差值是k,则两个i作为起点和终点的子序列就符合要求。由于起点就是最开始元素,只需遍历终点,时间复杂度为O(n)
public int subarraySum(int[] nums, int k) {        Map<Integer,Integer> map = new HashMap<Integer,Integer>();        map.put(0,1);        int sum = 0;        int res = 0;        for(int i = 0;i<nums.length;i++)        {            sum += nums[i];            res += map.getOrDefault(sum-k,0);            map.put(sum,map.getOrDefault(sum,0)+1);                     }        return res;    }

思路三:暴力,时间复杂度O(n^2)

0 0
原创粉丝点击