# Leetcode 刷题笔记 - 1

## 1、利用动态数组解决数据存放问题

``````输入：
N = 100

5 7 10 14 15 20 21 25 28 30 35 40 42 45 49 50 55 56 60 63 65 70 75 77 80 84 85 90 91 95 98 100

``````/**
* 利用动态数组解决数据存放问题
* @param {number[]} N
* @return {number[]}
*/

let dynamicArray = (N) = >{
if (N < 5) {
return []
}
let A = [] let base = 1
while (true) {
if (base * 5 <= N) {
A.push(base * 5) if (base * 7 <= N) {
A.push(base * 7)
}
base++
} else {
break
}
}
let res = Array.from(new Set([...A])) res = res.sort((a, b) = >{
return a - b
}) return res
}

## 2、托普利茨矩阵问题

``````输入:
matrix = [
[1,2,3,4],
[5,1,2,3],
[9,5,1,2]
]

``````/**
* 托普利茨矩阵问题
* @param {number[][]} matrix
* @return {boolean}
*/

let isToeplitzMatrix = (matrix) = >{
for (let i = 0; i < matrix.length - 1; i++) {
for (let j = 0; j < matrix[i].length - 1; j++) {
if (matrix[i][j] !== matrix[i + 1][j + 1]) {
return false
}
}
}
return true
}

## 3、三数之和

leetcode-cn.com/problems/3s…

``````给定数组 nums = [-1, 0, 1, 2, -1, -4]，

[
[-1, 0, 1],
[-1, -1, 2]
]

LeetCode 经典题（头条面试必考题），双指针 + 排序

``````/**
* 三数之和
* @param {number[]} nums
* @return {number[][]}
*/

let threeSum = (nums) = >{
nums.sort((a, b) = >{
return a - b
}) let result = []
for (let i = 0; i < nums.length; i++) {
if (i === 0 || nums[i] > nums[i - 1]) {
let j = i + 1 let k = nums.length - 1
while (j < k) {
s = nums[i] + nums[j] + nums[k]
if (s == 0) {
result.push([nums[i], nums[j], nums[k]]) j++;
k--;
while (j < k && nums[j] == nums[j - 1]) {
j++;
}
while (j < k && nums[k] == nums[k + 1]) {
k--;
}
} else if (s > 0) {
k--;
} else {
j++;
}
}
}
}
return result
}