sum-leetcode-560 subarray Sum Equals K

Source: Internet
Author: User

Title Description:

Given an array of integers and a 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: The length of the array is in range [1, 20,000]. The range of numbers in the array is [ -1000, +] and the range of the integerk is [ -1e7, 1e7]. idea One (recursive solution): Total equals the number of k = the number of consecutive and equal to K as the first element in the array + in addition to the first element, the remaining elements are contiguous and equal to K, code reference:

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);
    }

thinking Two (no thought, hash mapping): Traverse all the starting point is the first element of the sub-sequence, called Sum[i], as long as the difference of two sum[i] is K, then two I as the beginning and end of the sub-sequence to meet the requirements. Since the starting point is the first element, simply traverse the end point and the time complexity is O (n)

public int subarraysum (int[] nums, int k) {
        map<integer,integer> Map = new hashmap<integer,integer> (); C1/>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;
    }

idea Three: violence, time complexity O (n^2)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.