Skip to content

1——5

1.两数之和

解法1,哈希表:

java
public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> hashMap = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        if (hashMap.containsKey(target - nums[i])) {
            return new int[] {hashMap.get(target - nums[i]), i};
        }
        hashMap.put(nums[i], i);
    }
    throw new IllegalArgumentException("未找到");
}

解法2,暴力法:

java
public int[] twoSum(int[] nums, int target) {
    int n = nums.length;
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            if (nums[i] + nums[j] == target) {
                return new int[] {i, j};
            }
        }
    }
    throw new IllegalArgumentException("未找到");
}

2.两数相加

java
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummyHead = new ListNode(0); // 虚拟头节点
    ListNode current = dummyHead; // 当前节点
    int carry = 0; // 进位

    while (l1 != null || l2 != null || carry != 0) {
        int x = (l1 != null) ? l1.val : 0;
        int y = (l2 != null) ? l2.val : 0;
        int sum = carry + x + y;
        carry = sum / 10; // 更新进位
        current.next = new ListNode(sum % 10); // 创建新节点并添加到结果链表
        current = current.next; // 移动当前节点指针

        if (l1 != null) l1 = l1.next; // 移动l1指针
        if (l2 != null) l2 = l2.next; // 移动l2指针
    }

    return dummyHead.next; // 返回结果链表的头节点
    }

3.无重复字符的最长子串

Last updated: