一、基础数据结构实现
1. 用数组实现栈(LIFO)
class ArrayStack {
constructor() {
this.items = [];
}
// 入栈操作
push(element) {
this.items.push(element);
}
// 出栈操作
pop() {
if (this.isEmpty()) return null;
return this.items.pop();
}
// 查看栈顶元素
peek() {
return this.items[this.items.length - 1];
}
// 判空
isEmpty() {
return this.items.length === 0;
}
// 清空栈
clear() {
this.items = [];
}
}
// 测试用例
const stack = new ArrayStack();
stack.push('A');
stack.push('B');
console.log(stack.pop()); // B
console.log(stack.peek()); // A
2. 用数组实现队列(FIFO)
class ArrayQueue {
constructor() {
this.items = [];
}
// 入队
enqueue(element) {
this.items.push(element);
}
// 出队
dequeue() {
if (this.isEmpty()) return null;
return this.items.shift();
}
// 查看队首
front() {
return this.items[0];
}
// 判空
isEmpty() {
return this.items.length === 0;
}
// 获取大小
size() {
return this.items.length;
}
}
// 测试用例
const queue = new ArrayQueue();
queue.enqueue(1);
queue.enqueue(2);
console.log(queue.dequeue()); // 1
console.log(queue.front()); // 2
二、经典算法问题实战
1. 两数之和(哈希表优化版)
function twoSum(nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (map.has(complement)) {
return [map.get(complement), i];
}
map.set(nums[i], i);
}
return [];
}
// 测试
console.log(twoSum([2,7,11,15], 9)); // [0,1]
2. 旋转矩阵(原地算法)
function rotateMatrix(matrix) {
const n = matrix.length;
// 对角线翻转
for (let i = 0; i < n; i++) {
for (let j = i; j < n; j++) {
[matrix[i][j], matrix[j][i]] =
[matrix[j][i], matrix[i][j]];
}
}
// 水平翻转
for (let i = 0; i < n; i++) {
matrix[i].reverse();
}
}
/* 测试用例 */
const matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
];
rotateMatrix(matrix);
console.log(matrix);
/* 输出:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
*/
3. 合并有序数组(双指针法)
function mergeSortedArrays(arr1, arr2) {
let i = 0, j = 0;
const merged = [];
while (i < arr1.length && j < arr2.length) {
arr1[i] < arr2[j] ?
merged.push(arr1[i++]) :
merged.push(arr2[j++]);
}
return [...merged, ...arr1.slice(i), ...arr2.slice(j)];
}
// 测试
console.log(mergeSortedArrays([1,3,5], [2,4,6]));
// [1,2,3,4,5,6]
三、高级算法挑战
1. 三数之和(排序+双指针)
function threeSum(nums) {
nums.sort((a, b) => a - b);
const results = [];
for (let i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] === nums[i-1]) continue;
let left = i + 1;
let right = nums.length - 1;
while (left < right) {
const sum = nums[i] + nums[left] + nums[right];
if (sum === 0) {
results.push([nums[i], nums[left], nums[right]]);
while (left < right && nums[left] === nums[left+1]) left++;
while (left < right && nums[right] === nums[right-1]) right--;
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return results;
}
// 测试
console.log(threeSum([-1,0,1,2,-1,-4]));
// [[-1,-1,2], [-1,0,1]]
2. 接雨水问题(动态规划优化)
function trapRainWater(height) {
if (height.length < 3) return 0;
const leftMax = new Array(height.length).fill(0);
const rightMax = new Array(height.length).fill(0);
// 计算左侧最大值
leftMax[0] = height[0];
for (let i = 1; i < height.length; i++) {
leftMax[i] = Math.max(leftMax[i-1], height[i]);
}
// 计算右侧最大值
rightMax[height.length-1] = height[height.length-1];
for (let i = height.length-2; i >= 0; i--) {
rightMax[i] = Math.max(rightMax[i+1], height[i]);
}
// 计算总水量
let water = 0;
for (let i = 0; i < height.length; i++) {
water += Math.min(leftMax[i], rightMax[i]) - height[i];
}
return water;
}
// 测试
console.log(trapRainWater([0,1,0,2,1,0,1,3,2,1,2,1])); // 6
四、性能优化技巧
1. 时间复杂度对比
操作 | 时间复杂度 | 典型场景 |
---|---|---|
随机访问 | O(1) | arr[100] |
头尾增删 | O(1) | push/pop |
中间增删 | O(n) | splice |
查找元素 | O(n) | indexOf |
排序 | O(n logn) | sort |
2. 空间换时间策略
// 查找数组重复元素(Set优化版)
function findDuplicates(arr) {
const seen = new Set();
const duplicates = new Set();
for (const num of arr) {
seen.has(num) ? duplicates.add(num) : seen.add(num);
}
return Array.from(duplicates);
}
console.log(findDuplicates([1,2,3,2,4,3])); // [2,3]
五、综合训练场
1. 最长连续序列
function longestConsecutive(nums) {
const numSet = new Set(nums);
let longest = 0;
for (const num of numSet) {
if (!numSet.has(num-1)) {
let current = num;
let streak = 1;
while (numSet.has(current+1)) {
current++;
streak++;
}
longest = Math.max(longest, streak);
}
}
return longest;
}
console.log(longestConsecutive([100,4,200,1,3,2])); // 4
2. 数组全排列(回溯算法)
function permute(nums) {
const result = [];
function backtrack(path, used) {
if (path.length === nums.length) {
result.push([...path]);
return;
}
for (let i = 0; i < nums.length; i++) {
if (used[i]) continue;
used[i] = true;
path.push(nums[i]);
backtrack(path, used);
path.pop();
used[i] = false;
}
}
backtrack([], new Array(nums.length).fill(false));
return result;
}
console.log(permute([1,2,3]));
// [[1,2,3],[1,3,2],[2,1,3],...]
六、调试技巧
1. 可视化调试工具
使用Chrome DevTools的Array监控功能:
-
在Sources面板设置断点
-
使用Watch功能监控数组变化
const users = [
{name: 'Alice', age: 25},
{name: 'Bob', age: 30}
];
console.table(users);
2. 性能分析
使用performance API检测耗时操作:
const start = performance.now();
// 执行需要测试的数组操作
const end = performance.now();
console.log(`耗时:${end - start}ms`);
七、延伸思考
-
当数组长度超过V8引擎的快速元素限制时会发生什么?
-
如何用ArrayBuffer处理二进制数据?
-
为什么JavaScript数组的sort方法需要比较函数?
-
稀疏数组在内存中是如何存储的?
通过以上案例的系统练习,你将能够:
✅ 从容应对90%的数组相关面试题
✅ 掌握常见算法解题思路
✅ 写出高性能的数组操作代码
✅ 理解JavaScript数组的底层原理
如果你还有些别的想法,欢迎评论区留言啊