题目:
给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。
示例 1 :
输入:nums = [1,1,1], k = 2
输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
题解:
暴力一:O(N2)
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 = sum+ nums[end];
if (sum == k) {
count++;
}
}
}
return count;
}
}
public class Main{
public static void main(String[] args) {
int[] nums = {1,1,1};
int k = 2;
Solution p = new Solution();
int b = p.subarraySum(nums, k);
System.out.println("结果:" + b);
}
}
暴力二:O(N3)
public class Solution {
public int subarraySum(int[] nums, int k) {
int len = nums.length;
int count = 0;
for (int left = 0; left < len; left++) {
for (int right = left; right < len; right++) {
int sum = 0;
for (int i = left; i <= right; i++) {
sum += nums[i];
}
if (sum == k) {
count++;
}
}
}
return count;
}
public static void main(String[] args) {
int[] nums = new int[]{1, 1, 1};
int k = 2;
Solution solution = new Solution();
int res = solution.subarraySum(nums, k);
System.out.println(res);
}
}