问题1: 实现一个单链表的反转。
答案1: 可以使用迭代或递归来反转单链表。以下是迭代的解法。
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode current = head;
while (current != null) {
ListNode nextTemp = current.next;
current.next = prev;
prev = current;
current = nextTemp;
}
return prev;
}
}
问题2: 给定一个整数数组 nums,找到其中两个数使得它们的和等于一个特定的目标数。
答案2: 可以使用哈希表来解决此问题。以下是一个示例。
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}
问题3: 给定一个字符串 s,找到其中最长的回文子串。
答案3: 可以使用动态规划或中心扩展法来解决此问题。以下是中心扩展法的解法。
public class Solution {
public String longestPalindrome(String s) {
String longest = "";
for (int i = 0; i < s.length(); i++) {
String palindrome1 = expandAroundCenter(s, i, i);
String palindrome2 = expandAroundCenter(s, i, i + 1);
if (palindrome1.length() > longest.length()) {
longest = palindrome1;
}
if (palindrome2.length() > longest.length()) {
longest = palindrome2;
}
}
return longest;
}
private String expandAroundCenter(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return s.substring(left + 1, right);
}
}
问题4: 给定一个整数数组 nums,找到其中一个具有最大和的连续子数组(子数组最少包含一个元素)。
答案4: 可以使用动态规划来解决此问题。以下是一个示例。
public class Solution {
public int maxSubArray(int[] nums) {
int maxSum = nums[0];
int currentSum = nums[0];
for (int i = 1; i < nums.length; i++) {
currentSum = Math.max(nums[i], currentSum + nums[i]);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
}
问题5: 给定一个非空二叉树,返回其最大路径和。
答案5: 可以使用递归来解决此问题。以下是一个示例。
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public class Solution {
int maxSum = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
maxPathSumRecursive(root);
return maxSum;
}
private int maxPathSumRecursive(TreeNode node) {
if (node == null) {
return 0;
}
int leftMax = Math.max(0, maxPathSumRecursive(node.left));
int rightMax = Math.max(0, maxPathSumRecursive(node.right));
int currentMax = leftMax + rightMax + node.val;
maxSum = Math.max(maxSum, currentMax);
return Math.max(leftMax, rightMax) + node.val;
}
}
问题6: 实现一个有向图的深度优先搜索(DFS)算法,找出从指定起点到终点的路径。
答案6: 这是一个经典的深度优先搜索问题。以下是一个示例实现:
import java.util.*;
class Graph {
private int vertices;
private LinkedList<Integer>[] adjList;
public Graph(int vertices) {
this.vertices = vertices;
adjList = new LinkedList[vertices];
for (int i = 0; i < vertices; i++) {
adjList[i] = new LinkedList<>();
}
}
public void addEdge(int source, int destination) {
adjList[source].add(destination);
}
public List<Integer> findPath(int start, int end) {
List<Integer> path = new ArrayList<>();
boolean[] visited = new boolean[vertices];
dfs(start, end, visited, path);
return path;
}
private boolean dfs(int current, int end, boolean[] visited, List<Integer> path) {
visited[current] = true;
path.add(current);
if (current == end) {
return true;
}
for (int neighbor : adjList[current]) {
if (!visited[neighbor] && dfs(neighbor, end, visited, path)) {
return true;
}
}
path.remove(path.size() - 1);
return false;
}
}
public class Solution {
public static void main(String[] args) {
Graph graph = new Graph(6);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(2, 4);
graph.addEdge(3, 5);
int start = 0;
int end = 5;
List<Integer> path = graph.findPath(start, end);
if (!path.isEmpty()) {
System.out.println("Path from " + start + " to " + end + ": " + path);
} else {
System.out.println("No path found from " + start + " to " + end);
}
}
}
问题7: 实现一个二叉树的前序遍历(Preorder Traversal)。
答案7: 二叉树的前序遍历是一种深度优先搜索(DFS)算法,可以使用递归或迭代来实现。以下是一个递归实现的示例:
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
preorder(root, result);
return result;
}
private void preorder(TreeNode node, List<Integer> result) {
if (node == null) {
return;
}
result.add(node.val);
preorder(node.left, result);
preorder(node.right, result);
}
}
问题8: 实现一个LRU(Least Recently Used)缓存。
答案8: LRU缓存可以使用哈希表和双向链表来实现。以下是一个示例:
import java.util.*;
class LRUCache {
private final int capacity;
private final Map<Integer, Integer> cache;
private final Deque<Integer> accessOrder;
public LRUCache(int capacity) {
this.capacity = capacity;
cache = new HashMap<>(capacity);
accessOrder = new LinkedList<>();
}
public int get(int key) {
if (cache.containsKey(key)) {
accessOrder.remove(key);
accessOrder.addFirst(key);
return cache.get(key);
}
return -1;
}
public void put(int key, int value) {
if (cache.size() >= capacity) {
int leastRecentlyUsed = accessOrder.removeLast();
cache.remove(leastRecentlyUsed);
}
cache.put(key, value);
accessOrder.addFirst(key);
}
}
public class Solution {
public static void main(String[] args) {
LRUCache cache = new LRUCache(2);
cache.put(1, 1);
cache.put(2, 2);
System.out.println(cache.get(1)); // 输出 1
cache.put(3, 3); // 移除键 2
System.out.println(cache.get(2)); // 输出 -1 (未找到)
cache.put(4, 4); // 移除键 1
System.out.println(cache.get(1)); // 输出 -1 (未找到)
System.out.println(cache.get(3)); // 输出 3
System.out.println(cache.get(4)); // 输出 4
}
}