You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hello-algo/chapter_computational_compl.../space_time_tradeoff.md

382 lines
12 KiB

2 years ago
---
comments: true
---
2 years ago
# 2.4.   权衡时间与空间
2 years ago
2 years ago
理想情况下,我们希望算法的时间复杂度和空间复杂度都能达到最优。然而在实际情况中,同时优化时间复杂度和空间复杂度通常是非常困难的。
2 years ago
2 years ago
**降低时间复杂度通常需要以提升空间复杂度为代价,反之亦然**。我们将牺牲内存空间来提升算法运行速度的思路称为「以空间换时间」;反之,则称之为「以时间换空间」。
2 years ago
2 years ago
选择哪种思路取决于我们更看重哪个方面。在大多数情况下,时间比空间更宝贵,因此以空间换时间通常是更常用的策略。当然,在数据量很大的情况下,控制空间复杂度也是非常重要的。
2 years ago
2 years ago
## 2.4.1.   示例题目 *
2 years ago
以 LeetCode 全站第一题 [两数之和](https://leetcode.cn/problems/two-sum/) 为例。
!!! question "两数之和"
给定一个整数数组 `nums` 和一个整数目标值 `target` ,请你在该数组中找出“和”为目标值 `target` 的那两个整数,并返回它们的数组下标。
2 years ago
2 years ago
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
2 years ago
2 years ago
你可以按任意顺序返回答案。
2 years ago
「暴力枚举」和「辅助哈希表」分别对应“空间最优”和“时间最优”的两种解法。遵循时间比空间更宝贵的原则,后者是本题的最佳解法。
2 years ago
### 方法一:暴力枚举
2 years ago
考虑直接遍历所有可能的组合。通过开启一个两层循环,判断两个整数的和是否为 `target` ,若是,则返回它们的索引(即下标)。
2 years ago
=== "Java"
```java title="leetcode_two_sum.java"
/* 方法一:暴力枚举 */
2 years ago
int[] twoSumBruteForce(int[] nums, int target) {
int size = nums.length;
// 两层循环,时间复杂度 O(n^2)
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) {
if (nums[i] + nums[j] == target)
return new int[] { i, j };
2 years ago
}
}
2 years ago
return new int[0];
2 years ago
}
```
=== "C++"
```cpp title="leetcode_two_sum.cpp"
/* 方法一:暴力枚举 */
2 years ago
vector<int> twoSumBruteForce(vector<int> &nums, int target) {
2 years ago
int size = nums.size();
// 两层循环,时间复杂度 O(n^2)
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) {
if (nums[i] + nums[j] == target)
2 years ago
return {i, j};
2 years ago
}
}
2 years ago
return {};
}
2 years ago
```
=== "Python"
```python title="leetcode_two_sum.py"
2 years ago
def two_sum_brute_force(nums: list[int], target: int) -> list[int]:
2 years ago
"""方法一:暴力枚举"""
2 years ago
# 两层循环,时间复杂度 O(n^2)
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
2 years ago
return [i, j]
2 years ago
return []
2 years ago
```
=== "Go"
```go title="leetcode_two_sum.go"
2 years ago
/* 方法一:暴力枚举 */
2 years ago
func twoSumBruteForce(nums []int, target int) []int {
size := len(nums)
// 两层循环,时间复杂度 O(n^2)
for i := 0; i < size-1; i++ {
for j := i + 1; i < size; j++ {
if nums[i]+nums[j] == target {
return []int{i, j}
}
}
}
return nil
}
```
=== "JavaScript"
```javascript title="leetcode_two_sum.js"
2 years ago
/* 方法一:暴力枚举 */
2 years ago
function twoSumBruteForce(nums, target) {
const n = nums.length;
// 两层循环,时间复杂度 O(n^2)
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
return [];
}
```
=== "TypeScript"
```typescript title="leetcode_two_sum.ts"
2 years ago
/* 方法一:暴力枚举 */
2 years ago
function twoSumBruteForce(nums: number[], target: number): number[] {
const n = nums.length;
// 两层循环,时间复杂度 O(n^2)
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
return [];
};
```
=== "C"
```c title="leetcode_two_sum.c"
2 years ago
[class]{}-[func]{twoSumBruteForce}
2 years ago
```
=== "C#"
```csharp title="leetcode_two_sum.cs"
2 years ago
/* 方法一:暴力枚举 */
int[] twoSumBruteForce(int[] nums, int target)
2 years ago
{
2 years ago
int size = nums.Length;
// 两层循环,时间复杂度 O(n^2)
for (int i = 0; i < size - 1; i++)
2 years ago
{
2 years ago
for (int j = i + 1; j < size; j++)
2 years ago
{
2 years ago
if (nums[i] + nums[j] == target)
return new int[] { i, j };
2 years ago
}
}
2 years ago
return new int[0];
2 years ago
}
```
=== "Swift"
```swift title="leetcode_two_sum.swift"
2 years ago
/* 方法一:暴力枚举 */
2 years ago
func twoSumBruteForce(nums: [Int], target: Int) -> [Int] {
// 两层循环,时间复杂度 O(n^2)
for i in nums.indices.dropLast() {
for j in nums.indices.dropFirst(i + 1) {
if nums[i] + nums[j] == target {
return [i, j]
}
}
}
return [0]
}
```
=== "Zig"
```zig title="leetcode_two_sum.zig"
2 years ago
// 方法一:暴力枚举
2 years ago
fn twoSumBruteForce(nums: []i32, target: i32) ?[2]i32 {
2 years ago
var size: usize = nums.len;
var i: usize = 0;
// 两层循环,时间复杂度 O(n^2)
while (i < size - 1) : (i += 1) {
var j = i + 1;
while (j < size) : (j += 1) {
if (nums[i] + nums[j] == target) {
return [_]i32{@intCast(i32, i), @intCast(i32, j)};
2 years ago
}
}
}
2 years ago
return null;
2 years ago
}
2 years ago
```
2 years ago
该方法的时间复杂度为 $O(n^2)$ ,空间复杂度为 $O(1)$ **属于以时间换空间**。此方法时间复杂度太高,在大数据量下非常耗时。
2 years ago
2 years ago
### 方法二:辅助哈希表
2 years ago
考虑借助一个哈希表key-value 分别为数组元素和元素索引。循环遍历数组中的每个元素 num并执行
2 years ago
2 years ago
1. 判断数字 `target - num` 是否在哈希表中,若是则直接返回该两个元素的索引;
2. 将元素 `num` 和其索引添加进哈希表;
2 years ago
=== "Java"
```java title="leetcode_two_sum.java"
/* 方法二:辅助哈希表 */
2 years ago
int[] twoSumHashTable(int[] nums, int target) {
int size = nums.length;
// 辅助哈希表,空间复杂度 O(n)
Map<Integer, Integer> dic = new HashMap<>();
// 单层循环,时间复杂度 O(n)
for (int i = 0; i < size; i++) {
if (dic.containsKey(target - nums[i])) {
return new int[] { dic.get(target - nums[i]), i };
2 years ago
}
2 years ago
dic.put(nums[i], i);
2 years ago
}
2 years ago
return new int[0];
2 years ago
}
```
=== "C++"
```cpp title="leetcode_two_sum.cpp"
/* 方法二:辅助哈希表 */
2 years ago
vector<int> twoSumHashTable(vector<int> &nums, int target) {
2 years ago
int size = nums.size();
// 辅助哈希表,空间复杂度 O(n)
unordered_map<int, int> dic;
// 单层循环,时间复杂度 O(n)
for (int i = 0; i < size; i++) {
if (dic.find(target - nums[i]) != dic.end()) {
2 years ago
return {dic[target - nums[i]], i};
2 years ago
}
2 years ago
dic.emplace(nums[i], i);
2 years ago
}
2 years ago
return {};
}
2 years ago
```
=== "Python"
```python title="leetcode_two_sum.py"
2 years ago
def two_sum_hash_table(nums: list[int], target: int) -> list[int]:
2 years ago
"""方法二:辅助哈希表"""
2 years ago
# 辅助哈希表,空间复杂度 O(n)
dic = {}
# 单层循环,时间复杂度 O(n)
for i in range(len(nums)):
if target - nums[i] in dic:
2 years ago
return [dic[target - nums[i]], i]
2 years ago
dic[nums[i]] = i
return []
2 years ago
```
=== "Go"
```go title="leetcode_two_sum.go"
2 years ago
/* 方法二:辅助哈希表 */
2 years ago
func twoSumHashTable(nums []int, target int) []int {
// 辅助哈希表,空间复杂度 O(n)
hashTable := map[int]int{}
// 单层循环,时间复杂度 O(n)
for idx, val := range nums {
if preIdx, ok := hashTable[target-val]; ok {
return []int{preIdx, idx}
}
hashTable[val] = idx
}
return nil
}
```
=== "JavaScript"
```javascript title="leetcode_two_sum.js"
2 years ago
/* 方法二:辅助哈希表 */
2 years ago
function twoSumHashTable(nums, target) {
// 辅助哈希表,空间复杂度 O(n)
let m = {};
// 单层循环,时间复杂度 O(n)
for (let i = 0; i < nums.length; i++) {
if (m[nums[i]] !== undefined) {
return [m[nums[i]], i];
} else {
m[target - nums[i]] = i;
}
}
return [];
}
```
=== "TypeScript"
```typescript title="leetcode_two_sum.ts"
2 years ago
/* 方法二:辅助哈希表 */
2 years ago
function twoSumHashTable(nums: number[], target: number): number[] {
// 辅助哈希表,空间复杂度 O(n)
let m: Map<number, number> = new Map();
// 单层循环,时间复杂度 O(n)
for (let i = 0; i < nums.length; i++) {
let index = m.get(nums[i]);
if (index !== undefined) {
return [index, i];
} else {
m.set(target - nums[i], i);
}
}
return [];
};
```
=== "C"
```c title="leetcode_two_sum.c"
2 years ago
[class]{}-[func]{twoSumHashTable}
2 years ago
```
=== "C#"
```csharp title="leetcode_two_sum.cs"
2 years ago
/* 方法二:辅助哈希表 */
int[] twoSumHashTable(int[] nums, int target)
2 years ago
{
2 years ago
int size = nums.Length;
// 辅助哈希表,空间复杂度 O(n)
Dictionary<int, int> dic = new();
// 单层循环,时间复杂度 O(n)
for (int i = 0; i < size; i++)
2 years ago
{
2 years ago
if (dic.ContainsKey(target - nums[i]))
2 years ago
{
2 years ago
return new int[] { dic[target - nums[i]], i };
2 years ago
}
2 years ago
dic.Add(nums[i], i);
2 years ago
}
2 years ago
return new int[0];
2 years ago
}
```
=== "Swift"
```swift title="leetcode_two_sum.swift"
2 years ago
/* 方法二:辅助哈希表 */
2 years ago
func twoSumHashTable(nums: [Int], target: Int) -> [Int] {
// 辅助哈希表,空间复杂度 O(n)
var dic: [Int: Int] = [:]
// 单层循环,时间复杂度 O(n)
for i in nums.indices {
if let j = dic[target - nums[i]] {
return [j, i]
}
dic[nums[i]] = i
}
return [0]
}
```
=== "Zig"
```zig title="leetcode_two_sum.zig"
2 years ago
// 方法二:辅助哈希表
2 years ago
fn twoSumHashTable(nums: []i32, target: i32) !?[2]i32 {
2 years ago
var size: usize = nums.len;
// 辅助哈希表,空间复杂度 O(n)
var dic = std.AutoHashMap(i32, i32).init(std.heap.page_allocator);
defer dic.deinit();
var i: usize = 0;
// 单层循环,时间复杂度 O(n)
while (i < size) : (i += 1) {
if (dic.contains(target - nums[i])) {
return [_]i32{dic.get(target - nums[i]).?, @intCast(i32, i)};
2 years ago
}
2 years ago
try dic.put(nums[i], @intCast(i32, i));
2 years ago
}
2 years ago
return null;
2 years ago
}
2 years ago
```
2 years ago
2 years ago
该方法的时间复杂度为 $O(N)$ ,空间复杂度为 $O(N)$ **体现了以空间换时间**。尽管此方法引入了额外的空间使用,但在时间和空间的整体效率更为均衡,因此它是本题的最优解法。