From 57003c960134579e8b05a43bbeee3a5712212f28 Mon Sep 17 00:00:00 2001 From: juan Date: Mon, 5 Sep 2022 15:36:37 +0800 Subject: [PATCH] vault backup: 2022-09-05 15:36:37 --- .obsidian/graph.json | 2 +- .../pages/Leetcode Subarray-Sum-Equals-K.md | 103 ++++++++++++++++++ 2 files changed, 104 insertions(+), 1 deletion(-) create mode 100644 OJ notes/pages/Leetcode Subarray-Sum-Equals-K.md diff --git a/.obsidian/graph.json b/.obsidian/graph.json index 04297f8..ece4695 100644 --- a/.obsidian/graph.json +++ b/.obsidian/graph.json @@ -39,6 +39,6 @@ "repelStrength": 10, "linkStrength": 1, "linkDistance": 250, - "scale": 0.7878344292720599, + "scale": 0.7463733455586773, "close": true } \ No newline at end of file diff --git a/OJ notes/pages/Leetcode Subarray-Sum-Equals-K.md b/OJ notes/pages/Leetcode Subarray-Sum-Equals-K.md new file mode 100644 index 0000000..1ea15fb --- /dev/null +++ b/OJ notes/pages/Leetcode Subarray-Sum-Equals-K.md @@ -0,0 +1,103 @@ +# Leetcode Subarray-Sum-Equals-K + +2022-09-05 15:22 + +> ##### Algorithms: +> +> #algorithm #sliding_window #hash_table +> +> ##### Data structures: +> +> #DS +> +> ##### Difficulty: +> +> #coding_problem #difficulty-medium +> +> ##### Additional tags: +> +> #leetcode +> +> ##### Revisions: +> +> N/A + +##### Links: + +- [Link to problem](https://leetcode.com/problems/subarray-sum-equals-k/) + +--- + +### Problem + +Given an array of integers `nums` and an integer `k`, return _the total number of subarrays whose sum equals to_ `k`. + +A subarray is a contiguous **non-empty** sequence of elements within an array. + +#### Examples + +**Example 1:** + +**Input:** nums = [1,1,1], k = 2 +**Output:** 2 + +**Example 2:** + +**Input:** nums = [1,2,3], k = 3 +**Output:** 2 + +#### Constraints + +- `1 <= nums.length <= 2 * 104` +- `-1000 <= nums[i] <= 1000` +- `-107 <= k <= 107` + +### Thoughts + +> [!summary] +> This can be solved using #sliding_window + +> I over-complicated the solution by adding stuff like +> sorting, but it turn out to be not so difficult. + +Since the subsets are **contiguous**, we can use sliding +window here. + +### Solution + + +TLE, brute force +```cpp +class Solution { +public: + int subarraySum(vector &nums, int k) { + // O(N^2 / 2) + + int n = nums.size(); + + if (n == 1) { + return (k == nums[0]); + } + + vector prefix(n + 1, 0); + int prefixSum = 0; + + for (int i = 0; i < n; i++) { + prefixSum += nums[i]; + prefix[i + 1] = prefixSum; + } + + int count = 0; + + for (int i = 0; i < n + 1; i++) { + for (int j = i + 1; j < n + 1; j++) { + if (prefix[j] - prefix[i] == k) { + count++; + } + } + } + + return count; + } +}; +``` \ No newline at end of file