有没有佬会这个算法的用java写,已经不行了,燃尽了,问遍了ai也不行

下午好🌅🌅🌅
本答案参考通义千问
我理解你现在的心情,面试遇到算法题确实很考验心理素质和编程能力。不过别担心,我们可以一起分析这个问题,找到解决方案。
请告诉我具体的算法题目是什么?比如:
只有知道具体题目,我才能帮你写出 Java 代码实现,并详细解释思路和步骤。
给定一个整数数组
nums和一个目标值target,找出数组中和为target的两个数,并返回它们的下标。
public class TwoSum {
public static 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");
}
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
int[] result = twoSum(nums, target);
System.out.println("[" + result[0] + ", " + result[1] + "]");
}
}
反转一个单链表。
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class ReverseLinkedList {
public static 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;
}
public static void main(String[] args) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
node1.next = node2;
node2.next = node3;
ListNode reversed = reverseList(node1);
while (reversed != null) {
System.out.print(reversed.val + " -> ");
reversed = reversed.next;
}
}
}
public class Fibonacci {
// 递归方式(不推荐用于大数值)
public static int fibonacciRecursive(int n) {
if (n <= 1) return n;
return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);
}
// 迭代方式(推荐)
public static int fibonacciIterative(int n) {
if (n <= 1) return n;
int a = 0, b = 1;
for (int i = 2; i <= n; i++) {
int c = a + b;
a = b;
b = c;
}
return b;
}
public static void main(String[] args) {
System.out.println("Fibonacci(10) using recursive: " + fibonacciRecursive(10));
System.out.println("Fibonacci(10) using iterative: " + fibonacciIterative(10));
}
}
你可以直接贴出题目内容,我来帮你一步步解决!
别放弃,算法题是可以练出来的!加油! 🚀