Files
hello-algo/en/codes/java/chapter_computational_complexity/space_complexity.java
Yudong Jin 14c314c08c Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese

* Polish three English explanations after reader-focused review
2026-10-31 03:35:51 +08:00

111 lines
3.1 KiB
Java

/**
* File: space_complexity.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_computational_complexity;
import utils.*;
import java.util.*;
public class space_complexity {
/* Function */
static int function() {
// Perform some operations
return 0;
}
/* Constant complexity */
static void constant(int n) {
// Constants, variables, and objects occupy O(1) space
final int a = 0;
int b = 0;
int[] nums = new int[10000];
ListNode node = new ListNode(0);
// Variables in the loop occupy O(1) space
for (int i = 0; i < n; i++) {
int c = 0;
}
// Function calls in the loop occupy O(1) space
for (int i = 0; i < n; i++) {
function();
}
}
/* Linear complexity */
static void linear(int n) {
// An array of length n uses O(n) space
int[] nums = new int[n];
// A list of length n occupies O(n) space
List<ListNode> nodes = new ArrayList<>();
for (int i = 0; i < n; i++) {
nodes.add(new ListNode(i));
}
// A hash table with n entries occupies O(n) space
Map<Integer, String> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.put(i, String.valueOf(i));
}
}
/* Linear complexity (recursive implementation) */
static void linearRecur(int n) {
System.out.println("Recursive call: n = " + n);
if (n == 1)
return;
linearRecur(n - 1);
}
/* Quadratic complexity */
static void quadratic(int n) {
// The matrix uses O(n^2) space
int[][] numMatrix = new int[n][n];
// The two-dimensional list occupies O(n^2) space
List<List<Integer>> numList = new ArrayList<>();
for (int i = 0; i < n; i++) {
List<Integer> tmp = new ArrayList<>();
for (int j = 0; j < n; j++) {
tmp.add(0);
}
numList.add(tmp);
}
}
/* Quadratic complexity (recursive implementation) */
static int quadraticRecur(int n) {
if (n <= 0)
return 0;
// The lengths of array nums are n, n-1, ..., 2, 1
int[] nums = new int[n];
System.out.println("Recursive call: n = " + n + " with nums length = " + nums.length);
return quadraticRecur(n - 1);
}
/* Exponential complexity (building a perfect binary tree) */
static TreeNode buildTree(int n) {
if (n == 0)
return null;
TreeNode root = new TreeNode(0);
root.left = buildTree(n - 1);
root.right = buildTree(n - 1);
return root;
}
/* Driver code */
public static void main(String[] args) {
int n = 5;
// Constant complexity
constant(n);
// Linear complexity
linear(n);
linearRecur(n);
// Quadratic complexity
quadratic(n);
quadraticRecur(n);
// Exponential complexity
TreeNode root = buildTree(n);
PrintUtil.printTree(root);
}
}