力扣演算法JS LC 59-螺旋矩陣2,LC 152-乘積最大子數組
給你一個正整數 n
,生成一個包含 1
到 n2
所有元素,且元素按順時針順序螺旋排列的 n x n
正方形矩陣 matrix
。
示例 1:
輸入:n = 3
輸出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
輸入:n = 1
輸出:[[1]]
解題思路:根據左開右閉思想,依次對 上、右、下、左進行循環賦值,直到 num 等於n2 為止
程式碼:
var generateMatrix = function(n) {
// 創建一個 n * n 的數組
const matrix = new Array(n).fill(0).map(() => new Array(n).fill(0));
let num = 1; //設立初始值為 1
let left = 0, right = n - 1, top = 0, bottom = n - 1; //定義左右上下的初始值
while (num <= n * n) { //判斷是否還進行循環
for (let i = left; i <= right; i++) { //先循環上面一行
matrix[top][i] = num
num++
}
top++;
for (let i = top; i <= bottom; i++) { //右邊
matrix[i][right] = num
num++;
}
right--;
for (let i = right; i >= left; i--) { //下面
matrix[bottom][i] = num
num++;
}
bottom--;
for (let i = bottom; i >= top; i--) { //左邊
matrix[i][left] = num
num++;
}
left++;
}
return matrix;
};
LC 152-乘積最大子數組
給你一個整數數組 nums ,請你找出數組中乘積最大的非空連續子數組(該子數組中至少包含一個數字),並返回該子數組所對應的乘積。
測試用例的答案是一個 32-位 整數。
子數組 是數組的連續子序列。
示例 1:
輸入: nums = [2,3,-2,4]
輸出: 6
解釋: 子數組 [2,3] 有最大乘積 6。
示例 2:
輸入: nums = [-2,0,-1]
輸出: 0
解釋: 結果不能為 2, 因為 [-2,-1] 不是子數組。
解題思路:需要考慮數值的正負問題。所以要找出每個小範圍內的最小值與最大值,然後進行比對。最後得出整個數組的最大值
程式碼:
var maxProduct = function(nums) {
let res = nums[0]; //最後要輸出的結果
let maxs = nums[0]; //存儲最大值
let mins = nums[0]; //存儲最小值
let temp1 = 0, temp2 = 0; //中間存儲量
for(let i = 1; i < nums.length; i++) {
temp1 = maxs * nums[i];
temp2 = mins * nums[i];
maxs = Math.max(temp1, temp2, nums[i]);
mins = Math.min(temp1, temp2, nums[i]);
res = Math.max(maxs, res);
}
return res;
};