使用 JavaScript 掌握 DSA 中的数组操作:从基础到高级
掌握 DSA JavaScript 中的数组操作
数组是计算机科学中的基本数据结构,广泛应用于各种算法和问题解决场景中。这份综合指南将带您了解 JavaScript 中数组操作的基础知识,涵盖从基础到高级的主题。我们将探索遍历、插入、删除、搜索等,以及它们的时间复杂度和实际示例。
目录
- 数组简介
- 数组遍历
- 插入数组
- 数组中的删除
- 在数组中搜索
- 高级数组操作技术
- 练习题
- LeetCode 问题链接
1. 数组简介
数组是存储在连续内存位置的元素的集合。在 JavaScript 中,数组是动态的,可以保存不同类型的元素。
基本数组操作:
// Creating an array let arr = [1, 2, 3, 4, 5]; // Accessing elements console.log(arr[0]); // Output: 1 // Modifying elements arr[2] = 10; console.log(arr); // Output: [1, 2, 10, 4, 5] // Getting array length console.log(arr.length); // Output: 5
时间复杂度:
- 访问元素:O(1)
- 修改元素:O(1)
- 获取数组长度:O(1)
2. 数组遍历
遍历意味着访问数组的每个元素一次。在 JavaScript 中,有多种方法可以遍历数组。
2.1 使用for循环
let arr = [1, 2, 3, 4, 5]; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); }
时间复杂度:O(n),其中 n 是数组中元素的数量。
2.2 使用forEach
let arr = [1, 2, 3, 4, 5]; arr.forEach(element => console.log(element));
时间复杂度:O(n)
2.3 使用for...of循环
let arr = [1, 2, 3, 4, 5]; for (let element of arr) { console.log(element); }
时间复杂度:O(n)
3. 数组中的插入
可以在数组的开头、结尾或特定位置插入。
3.1 末尾插入
let arr = [1, 2, 3]; arr.push(4); console.log(arr); // Output: [1, 2, 3, 4]
时间复杂度:O(1)(摊销)
3.2 在开头插入
let arr = [1, 2, 3]; arr.unshift(0); console.log(arr); // Output: [0, 1, 2, 3]
时间复杂度:O(n),因为所有现有元素都需要移动
3.3 在特定位置插入
let arr = [1, 2, 4, 5]; arr.splice(2, 0, 3); console.log(arr); // Output: [1, 2, 3, 4, 5]
时间复杂度:O(n),因为插入点之后的元素需要移动
4. 数组中的删除
与插入类似,删除可以在开头、结尾或特定位置进行。
4.1 从末尾删除
let arr = [1, 2, 3, 4]; arr.pop(); console.log(arr); // Output: [1, 2, 3]
时间复杂度:O(1)
4.2 从头删除
let arr = [1, 2, 3, 4]; arr.shift(); console.log(arr); // Output: [2, 3, 4]
时间复杂度:O(n),因为所有剩余元素都需要移位
4.3 特定位置的删除
let arr = [1, 2, 3, 4, 5]; arr.splice(2, 1); console.log(arr); // Output: [1, 2, 4, 5]
时间复杂度:O(n),因为删除点之后的元素需要移位
5. 在数组中搜索
搜索是对数组执行的常见操作。让我们看看一些搜索技巧。
5.1 线性搜索
function linearSearch(arr, target) { for (let i = 0; i < arr.length; i++) { if (arr[i] === target) return i; } return -1; } let arr = [1, 3, 5, 7, 9]; console.log(linearSearch(arr, 5)); // Output: 2 console.log(linearSearch(arr, 6)); // Output: -1
时间复杂度:O(n)
5.2 二分查找(对于排序数组)
function binarySearch(arr, target) { let left = 0, right = arr.length - 1; while (left <= right) { let mid = Math.floor((left + right) / 2); if (arr[mid] === target) return mid; if (arr[mid] < target) left = mid + 1; else right = mid - 1; } return -1; } let arr = [1, 3, 5, 7, 9]; console.log(binarySearch(arr, 5)); // Output: 2 console.log(binarySearch(arr, 6)); // Output: -1
时间复杂度:O(log n)
6. 先进的数组操作技术
现在让我们探索一些更高级的数组操作技术。
6.1 两指针技术
两指针技术经常被用来有效地解决数组问题。这是使用两个指针就地反转数组的示例:
function reverseArray(arr) { let left = 0, right = arr.length - 1; while (left < right) { [arr[left], arr[right]] = [arr[right], arr[left]]; left++; right--; } } let arr = [1, 2, 3, 4, 5]; reverseArray(arr); console.log(arr); // Output: [5, 4, 3, 2, 1]
时间复杂度:O(n)
6.2 滑动窗口技术
滑动窗口技术对于解决子数组问题很有用。下面是一个查找大小为 k 的最大和子数组的示例:
function maxSumSubarray(arr, k) { let maxSum = 0; let windowSum = 0; // Calculate sum of first window for (let i = 0; i < k; i++) { windowSum += arr[i]; } maxSum = windowSum; // Slide the window for (let i = k; i < arr.length; i++) { windowSum = windowSum - arr[i - k] + arr[i]; maxSum = Math.max(maxSum, windowSum); } return maxSum; } let arr = [1, 4, 2, 10, 23, 3, 1, 0, 20]; console.log(maxSumSubarray(arr, 4)); // Output: 39
时间复杂度:O(n)
6.3 Kadane算法
Kadane 算法用于查找数组中的最大子数组和。这是动态规划的一个例子:
function kadane(arr) { let maxSoFar = arr[0]; let maxEndingHere = arr[0]; for (let i = 1; i < arr.length; i++) { maxEndingHere = Math.max(arr[i], maxEndingHere + arr[i]); maxSoFar = Math.max(maxSoFar, maxEndingHere); } return maxSoFar; } let arr = [-2, -3, 4, -1, -2, 1, 5, -3]; console.log(kadane(arr)); // Output: 7
时间复杂度:O(n)
6.4 荷兰国旗算法
该算法用于对仅包含 0、1 和 2 的数组进行排序:
function dutchNationalFlag(arr) { let low = 0, mid = 0, high = arr.length - 1; while (mid <= high) { if (arr[mid] === 0) { [arr[low], arr[mid]] = [arr[mid], arr[low]]; low++; mid++; } else if (arr[mid] === 1) { mid++; } else { [arr[mid], arr[high]] = [arr[high], arr[mid]]; high--; } } } let arr = [2, 0, 1, 2, 1, 0]; dutchNationalFlag(arr); console.log(arr); // Output: [0, 0, 1, 1, 2, 2]
时间复杂度:O(n)
7. 练习题
这里有 50 个练习题,从简单到高级。其中一些来自 LeetCode,而另一些则是常见的数组操作场景:
- Sum all elements in an array
- Find the maximum element in an array
- Reverse an array in-place
- Remove duplicates from a sorted array
- Rotate an array by k steps
- Find the second largest element in an array
- Merge two sorted arrays
- Find the missing number in an array of 1 to n
- Move all zeros to the end of the array
- Find the intersection of two arrays
- Find the union of two arrays
- Check if an array is a subset of another array
- Find the equilibrium index in an array
- Rearrange positive and negative numbers in an array
- Find the majority element in an array
- Find the peak element in an array
- Implement a circular array
- Find the smallest positive missing number in an array
- Trapping Rain Water problem
- Implement a stack using an array
- Implement a queue using an array
- Find the longest increasing subsequence
- Implement binary search in a rotated sorted array
- Find the maximum sum of a subarray of size k
- Implement the Kadane's algorithm
- Find the minimum number of platforms required for a railway station
- Find the longest subarray with equal number of 0s and 1s
- Implement the Dutch National Flag algorithm
- Find the smallest subarray with sum greater than a given value
- Implement the Boyer-Moore Majority Voting algorithm
- Find the maximum product subarray
- Implement the Jump Game algorithm
- Find the next greater element for every element in an array
- Implement the Sliding Window Maximum algorithm
- Find the longest substring without repeating characters
- Implement the Merge Intervals algorithm
- Find the minimum number of jumps to reach the end of an array
- Implement the Stock Buy Sell to Maximize Profit algorithm
- Find the Longest Palindromic Substring
- Implement the Longest Common Subsequence algorithm
- Find the Shortest Unsorted Continuous Subarray
- Implement the Container With Most Water algorithm
- Find the Longest Consecutive Sequence in an array
- Implement the Maximum Product of Three Numbers algorithm
- Find the Kth Largest Element in an Array
- Implement the Find All Duplicates in an Array algorithm
- Find the Minimum Size Subarray Sum
- Implement the Product of Array Except Self algorithm
- Find the Maximum Gap in a sorted array
- Implement the Median of Two Sorted Arrays algorithm
8. LeetCode Problem Links
Here are 20 LeetCode problems to test your array manipulation skills:
- Two Sum
- Best Time to Buy and Sell Stock
- Contains Duplicate
- Product of Array Except Self
- Maximum Subarray
- Merge Intervals
- 3Sum
- Container With Most Water
- Rotate Array
- Search in Rotated Sorted Array
- Find Minimum in Rotated Sorted Array
- Next Permutation
- Subarray Sum Equals K
- Spiral Matrix
- Jump Game
- Longest Consecutive Sequence
- Find All Duplicates in an Array
- Kth Largest Element in an Array
- Trapping Rain Water
- Median of Two Sorted Arrays
By working through these problems and understanding the underlying concepts, you'll significantly improve your array manipulation skills in JavaScript for Data Structures and Algorithms.
Remember, the key to mastering these techniques is consistent practice and understanding the time and space complexities of your solutions.
Happy coding!
以上是使用 JavaScript 掌握 DSA 中的数组操作:从基础到高级的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

JavaScript在Web开发中的主要用途包括客户端交互、表单验证和异步通信。1)通过DOM操作实现动态内容更新和用户交互;2)在用户提交数据前进行客户端验证,提高用户体验;3)通过AJAX技术实现与服务器的无刷新通信。

JavaScript在现实世界中的应用包括前端和后端开发。1)通过构建TODO列表应用展示前端应用,涉及DOM操作和事件处理。2)通过Node.js和Express构建RESTfulAPI展示后端应用。

理解JavaScript引擎内部工作原理对开发者重要,因为它能帮助编写更高效的代码并理解性能瓶颈和优化策略。1)引擎的工作流程包括解析、编译和执行三个阶段;2)执行过程中,引擎会进行动态优化,如内联缓存和隐藏类;3)最佳实践包括避免全局变量、优化循环、使用const和let,以及避免过度使用闭包。

Python和JavaScript在社区、库和资源方面的对比各有优劣。1)Python社区友好,适合初学者,但前端开发资源不如JavaScript丰富。2)Python在数据科学和机器学习库方面强大,JavaScript则在前端开发库和框架上更胜一筹。3)两者的学习资源都丰富,但Python适合从官方文档开始,JavaScript则以MDNWebDocs为佳。选择应基于项目需求和个人兴趣。

Python和JavaScript在开发环境上的选择都很重要。1)Python的开发环境包括PyCharm、JupyterNotebook和Anaconda,适合数据科学和快速原型开发。2)JavaScript的开发环境包括Node.js、VSCode和Webpack,适用于前端和后端开发。根据项目需求选择合适的工具可以提高开发效率和项目成功率。

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。 1)C 用于解析JavaScript源码并生成抽象语法树。 2)C 负责生成和执行字节码。 3)C 实现JIT编译器,在运行时优化和编译热点代码,显着提高JavaScript的执行效率。

JavaScript在网站、移动应用、桌面应用和服务器端编程中均有广泛应用。1)在网站开发中,JavaScript与HTML、CSS一起操作DOM,实现动态效果,并支持如jQuery、React等框架。2)通过ReactNative和Ionic,JavaScript用于开发跨平台移动应用。3)Electron框架使JavaScript能构建桌面应用。4)Node.js让JavaScript在服务器端运行,支持高并发请求。
