字节跳动笔试题:560.和为K的子数组

题目抽象出来为:
要求找到数组的子数组满足某个要求

image

image

方法一:枚举法:

子数组的一个特点就是,他有头有尾,也就是说两个变量就可以截取出来一个子数组,

public class Solution {
    public int subarraySum(int[] nums, int k) {
        int count = 0;
        for (int start = 0; start < nums.length; ++start) {
            int sum = 0;
            for (int end = start; end >= 0; --end) {
                sum += nums[end];
                if (sum == k) {
                    count++;
                }
            }
        }
        return count;
    }
}

posted @ 2026-08-04 21:51  Jwwind  阅读(2)  评论(0)    收藏  举报