Java知识分享网 - 轻松学习从此开始!    

Java知识分享网

        
AI编程,程序员挑战年入30~100万高级指南 - 职业规划
SpringBoot+SpringSecurity+Vue权限系统高级实战课程        

IDEA永久激活

Java微信小程序电商实战课程(SpringBoot+VUe)

     

AI人工智能学习大礼包

     

PyCharm永久激活

66套java实战课程无套路领取

     

Cursor+Claude AI编程 1天快速上手视频教程

     

基于Java实现20道LeetCode题 PDF 下载


时间:2024-08-22 11:15来源:http://www.java1234.com 作者:转载  侵权举报
基于Java实现20道LeetCode题
失效链接处理
基于Java实现20道LeetCode题 PDF 下载

 
 
相关截图:
 


主要内容:


1. 两数之和 (Two Sum)
解题思路
使用哈希表存储每个数字的索引,如果某个数字的补数存在于哈希表中,则返回对应的索引。
实现代码
 
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");
}
}

 

2. 添加两数 (Add Two Numbers)
解题思路
使用链表表示两个数,从最低位开始逐位相加,注意处理进位。
实现代码
 
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, current = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
current.next = new ListNode(sum % 10);
current = current.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) {
current.next = new ListNode(carry);
}
return dummyHead.next;
}
}

 



 


------分隔线----------------------------


锋哥推荐