算法汇总
记性不好,每次都要从头开始做题,算法还是必刷,写在这里记录一下吧。
1. 两数之和
class Solution {
// key是nums[i] value是我们最终得到的数组值
// 思路:使用HashMap存储数据元素,检查 补充数字是否存在,如果存在说明之前遍历过该元素,如果不存在存入哈西表
// 时间复杂度 O(1) 数组遍历一次; 空间复杂度 O(n) 需要遍历哈西表中所有元素
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> numsMap =new HashMap<Integer,Integer>();
for (int i =0 ; i < nums.length; i++){
int comple = target - nums[i];
if (numsMap.containsKey(comple)){
return new int[]{numsMap.get(comple),i};
}else{
numsMap.put(nums[i],i);
}
}
return new int[0];
}
}
2. 两数相加
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
//head:指向链表的头部,用于后续返回整个链表。
//tail:指向链表的尾部,用于高效地在链表末尾添加新节点
//思路: 逐位相加,处理进位
//时间复杂度 O(max(m, n))
//空间复杂度 O(max(m, n))
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null, tail = null;
int carry = 0;
while (l1 != null || l2 != null) {
//注意这里是判断l1
int n1 = l1 != null ? l1.val : 0;
int n2 = l2 != null ? l2.val : 0;
int sum = n1 + n2 + carry;
if (head == null) {
head = tail = new ListNode(sum % 10);
} else {
tail.next = new ListNode(sum % 10);
tail = tail.next;
}
carry = sum / 10;
if (l1 != null) l1 = l1.next;
if (l2 != null) l2 = l2.next;
}
//别忘记还有carry
if (carry > 0) {
tail.next = new ListNode(carry);
}
return head;
}
}