week16- NO.560. Subarray Sum Equals K

来源:互联网 发布:装个博卡软件多少钱 编辑:程序博客网 时间:2024/06/06 03:28

题目

  • Total Accepted: 7722
  • Total Submissions: 18808
  • 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].
https://leetcode.com/problems/subarray-sum-equals-k/#/description

思路

题目给定一个整数数组,和一个整数k,希望求得数组中使得总和为k的子数组的个数
使用暴力穷举,先使用一个数组sum,其中sum[i]保存数组前i个数的和,则sum[j] - sum[i]得到的就是数组中第i到j的子数组的总和。遍历i,j,则能得到需要的解。

源程序

class Solution {public:    int subarraySum(vector<int>& nums, int k) {        if(nums.size() == 0)            return 0;        int sum[20001];        int i,j;        int count = 0;        sum[0] = 0;        for(i = 1;i <= nums.size();i ++)            sum[i] = sum[i - 1] + nums[i - 1];        for(i = 0;i < nums.size();i ++)            for(j = i + 1; j <= nums.size();j ++)                if(sum[j] - sum[i] == k)                    count ++;        return count;    }};


原创粉丝点击