Java 面试中必备的 5 道代码题284


在 Java 面试中,代码题是一个必不可少的部分。它们能够评估候选人的编程能力、问题解决能力和对 Java 语言的理解程度。本文精挑细选了 5 道 Java 面试中经常出现的代码题,涵盖了从基本语法到高级数据结构和算法的各种方面。通过解决这些代码题,你可以提升自己的 Java 编程技能并为面试做好充分的准备。

1. 反转一个整数

题目:编写一个方法,将一个给定的整数反转。例如,输入 123,输出 321;输入 -123,输出 -321。
public class ReverseInteger {
public static void main(String[] args) {
int num = 123;
(reverse(num)); // 321
num = -123;
(reverse(num)); // -321
}
public static int reverse(int num) {
int reversed = 0;
while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
return reversed;
}
}

2. 找出字符串中的第一个不重复的字符

题目:给定一个字符串,找出其中第一个不重复的字符。例如,输入 "leetcode",输出 "l";输入 "loveleetcode",输出 "v"。
public class FirstUniqueCharacter {
public static void main(String[] args) {
String str = "leetcode";
(firstUniqChar(str)); // "l"
str = "loveleetcode";
(firstUniqChar(str)); // "v"
}
public static char firstUniqChar(String str) {
int[] charCount = new int[256];
for (char c : ()) {
charCount[c]++;
}
for (char c : ()) {
if (charCount[c] == 1) {
return c;
}
}
return ' ';
}
}

3. 实现队列数据结构

题目:用 Java 实现一个队列数据结构,支持 `add()`、`remove()` 和 `peek()` 操作。队列是一种先进先出的 (FIFO) 数据结构。
public class Queue {
private Node head;
private Node tail;
public void add(int data) {
Node newNode = new Node(data);
if (tail == null) {
head = newNode;
tail = newNode;
} else {
= newNode;
tail = newNode;
}
}
public int remove() {
if (head == null) {
return -1;
}
int data = ;
head = ;
if (head == null) {
tail = null;
}
return data;
}
public int peek() {
if (head == null) {
return -1;
}
return ;
}
}
public class Node {
int data;
Node next;
public Node(int data) {
= data;
= null;
}
}

4. 找出数组中的最大和子数组

题目:给定一个整型数组,找出其连续子数组的最大和。例如,输入 `[-2, 1, -3, 4, -1, 2, 1, -5, 4]`, 输出 6。
public class MaximumSubarray {
public static void main(String[] args) {
int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
(maxSubArray(nums)); // 6
}
public static int maxSubArray(int[] nums) {
int maxSum = Integer.MIN_VALUE;
int currentSum = 0;
for (int num : nums) {
currentSum = (num, currentSum + num);
maxSum = (maxSum, currentSum);
}
return maxSum;
}
}

5. 二叉树的最大深度

题目:给定一棵二叉树,求其最大深度。最大深度定义为从根节点到最远叶节点的最长路径长度。例如,对于以下二叉树:


1
/ \
2 3
/ \
4 5

输出应为 3。
public class MaxDepthOfBinaryTree {
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
= new TreeNode(2);
= new TreeNode(3);
= new TreeNode(4);
= new TreeNode(5);
(maxDepth(root)); // 3
}
public static int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = maxDepth();
int rightDepth = maxDepth();
return (leftDepth, rightDepth) + 1;
}
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
= val;
= null;
= null;
}
}

通过掌握这些代码题,你将大幅提升自己的 Java 编程能力和面试表现。祝你好运,期待你在 Java 之路上取得成功!

2024-12-05


上一篇:Java消消乐游戏制作指南

下一篇:Java 中如何优雅地移除字符串首尾字符