一、Leetcode题精选
1. 两数之和 要求:空间复杂度 O(n),时间复杂度 O(nlogn)
牛客网返回数字位置从1开始
import java.util.*;
public class Solution {
/**
*
* @param numbers int整型一维数组
* @param target int整型
* @return int整型一维数组
*/
public int[] twoSum (int[] nums, int target) {
// write code here
Map<Integer,Integer> hashtable = new HashMap<>();
for (int i = 0; i < nums.length; ++i) {
if (hashtable.containsKey(target - nums[i])) {
// 匿名对象数组
return new int[]{hashtable.get(target-nums[i])+1,i+1};
}
hashtable.put(nums[i],i);
}
return new int[0];
}
}
leetcode返回索引位置从0开始
import java.util.*;
public class Solution {
/**
*
* @param numbers int整型一维数组
* @param target int整型
* @return int整型一维数组
*/
public int[] twoSum (int[] nums, int target) {
// write code here
Map<Integer,Integer> hashtable = new HashMap<>();
for (int i = 0; i < nums.length; ++i) {
if (hashtable.containsKey(target - nums[i])) {
// 匿名对象数组
return new int[]{hashtable.get(target-nums[i]),i};
}
hashtable.put(nums[i],i);
}
return new int[0];
}
}
时间复杂度:O(N),其中 N是数组中的元素数量。对于每一个元素 x,我们可以 O(1)地寻找 target - x。
空间复杂度:O(N),其中 N是数组中的元素数量。主要为哈希表的开销。
2. 爬楼梯
class Solution {
public int climbStairs(int n) {
// 动态规划用滚动数组的方法实现了对空间的优化,时间复杂度O(n),空间复杂度O(1)
if (n == 1) return 1;
if (n == 2) return 2;
int p = 0, q = 0, r = 1;
for (int i = 1; i <= n; ++i) {
p = q;
q = r;
r = p + q;
}
return r;
}
}
3. 翻转二叉树
class Solution {
public TreeNode invertTree(TreeNode root) {
// 递归的出口
if (root == null) return null;
TreeNode left = invertTree(root.left);
TreeNode right = invertTree(root.right);
// 递归的分解
root.left = right;
root.right = left;
return root;
}
}
时间复杂度:O(N),其中 N为二叉树节点的数目。我们会遍历二叉树中的每一个节点,对每个节点而言,我们在常数时间内交换其两棵子树。
空间复杂度:O(N)。使用的空间由递归栈的深度决定,它等于当前节点在二叉树中的高度。在平均情况下,二叉树的高度与节点个数为对数关系,即 O(logN)。而在最坏情况下,树形成链状,空间复杂度为 O(N)。
4. 反转链表
要求:空间复杂度 O(1) ,时间复杂度 O(n)。
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) return null;
ListNode prevNode = null;
while (head != null) {
ListNode next = head.next;
head.next = prevNode;
prevNode = head;
head = next;
}
return prevNode;
}
}
时间复杂度:O(n),其中 n是链表的长度。需要遍历链表一次。
空间复杂度:O(1)。
5. LRU缓存机制
有参构造函数和无参构造函数的区别_E=mc²-CSDN博客_有参构造函数和无参构造函数的区别
头结点是最近缓存使用的
cache.put(1, 1); head <=> (1,(1,1)) <=> tail
cache.put(2, 2); head <=> (2,(2,2)) <=> (1,(1,1)) <=> tail
cache.get(1); // 返回 1 head <=> (1,(1,1)) <=> (2,(2,2)) <=> tail
cache.put(3, 3); // 该操作会使得密钥 2 作废 head <=> (3,(3,3)) <=> (1,(1,1)) <=> tail
cache.get(2); // 返回 -1 (未找到 )
cache.put(4, 4); // 该操作会使得密钥 1 作废 head <=> (4,(4,4)) <=> (3,(3,3)) <=> tail
cache.get(1); // 返回 -1 (未找到 )
cache.get(3); // 返回 3 head <=> (3,(3,3)) <=> (4,(4,4)) <=> tail