Day2-Array02

Guoyi Lv3

209. Minimum Size Subarray Sum

Note:

  • sliding window: a fixed or variable-size window is moved through a data structure, to solve problems efficiently based on continous subsets of elements. It’s used to find subarrays or substrings to a given set of conditions
    • start index: how to move it?
    • increase the start index when meet the condition
    • end index: how to move it?
    • use for loop to keep increase the end index
    • from start to end, what are inside the scope?

Time Complexity && Space Complexity

  • Time Complexity: O(n)
    • when moving the window, every element is added to sum for one time, is deleted from the sum for one time
  • Space Complexity: O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* @param {number} target
* @param {number[]} nums
* @return {number}
*/
var minSubArrayLen = function (target, nums) {
let ans = Number.MAX_SAFE_INTEGER;

let i = 0;
let j = 0;
let sum = 0;
while (j < nums.length) {
sum += nums[j];
while (sum >= target && i < nums.length) {
ans = Math.min(ans, j - i + 1);
sum -= nums[i];
i++;
}
j++;
}
return ans == Number.MAX_SAFE_INTEGER ? 0 : ans;
};

59. Spiral Matrix II

Note:

  • every for loop only include the left, exclude the right, which could keep the consistent

Time Complexity && Space Complexity

  • Time Complexity: O(n^2)
    • when moving the window, every element is added to sum for one time, is deleted from the sum for one time
  • Space Complexity: O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function (n) {
const res = new Array(n).fill().map(() => new Array(n).fill(0));
let value = 1;
let row = 0;
let col = 0;
let offSet = 1;
let start = 0;
let loop = Math.floor(n / 2);
// all need be [left, right)
// keep safe will make the code easy
while (loop > 0) {
let row = start,
col = start;
for (; col < n - offSet; col++) {
res[row][col] = value;
value++;
}
for (; row < n - offSet; row++) {
res[row][col] = value;
value++;
}
for (; col > start; col--) {
res[row][col] = value;
value++;
}
for (; row > start; row--) {
res[row][col] = value;
value++;
}
start++;
offSet++;
loop--;
}
let mid = Math.floor(n / 2);
if (n % 2 == 1) {
res[mid][mid] = n * n;
}
return res;
};
  • Title: Day2-Array02
  • Author: Guoyi
  • Created at : 2024-08-23 09:35:17
  • Updated at : 2024-12-07 03:58:41
  • Link: https://guoyiwang.github.io/Algorithm/Day2-Array02/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments