LeetCode——560. The sum is a sub-array of K

Title description:

Given an integer array and an integer k, you need to find the number of consecutive sub-arrays that sum to k in the array.

Example 1:
Input: nums = [1,1,1], k = 2
Output: 2, [1,1] and [1,1] are two different situations.

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

code show as below:

Prefix and:

class Solution {
    
    
    public int subarraySum(int[] nums, int k) {
    
    
        int n = nums.length;
        int[] arr = new int[n + 1];
        arr[0] = 0;
        for (int i = 0; i < n; i++) {
    
    
            arr[i + 1] = arr[i] + nums[i];
        }
        int ans = 0;
        for (int i = 1; i <= n; i++) {
    
    
            for (int j = 0; j < i; j++) {
    
    
                if (arr[i] - arr[j] == k) {
    
    
                    ans++;
                }
            }
        }
        return ans;
    }
}

violence:

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

Results of the:
Insert picture description here

Guess you like

Origin blog.csdn.net/FYPPPP/article/details/114748882