20200901-1. 两数之和,2. 两数之和

  1. 两数之和


    image.png
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int len = nums.length;
        int []result = new int[2];
        Map<Integer, Integer> map = new HashMap<>(len);
        for (int i=0;i<nums.length;i++) {
            int temp = target - nums[i];
            if (map.containsKey(temp)) {
                result[0] = map.get(temp);
                result[1] = i;
                break;
            }
            map.put(nums[i], i);
        }
        return result;
    }
}
  1. 两数之和


    image.png
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode current = new ListNode(0);
        ListNode pre = current;
        boolean moreThanTen = false;
        while (l1 != null && l2 != null) {
            int val = l1.val + l2.val;
            if (moreThanTen) {
                val = val + 1;
                moreThanTen = false;
            }
            if (val > 9) {
                val = val - 10;
                moreThanTen = true;
            }
            ListNode l = new ListNode(val);
            current.next = l;
            current = l;
            l1 = l1.next;
            l2 = l2.next;
        }
        while (l1 != null) {
            int val = l1.val;
            if (moreThanTen) {
                val = val + 1;
                moreThanTen = false;
            }
            if (val > 9) {
                val = val - 10;
                moreThanTen = true;
            }
            ListNode l = new ListNode(val);
            current.next = l;
            current = l;
            l1 = l1.next;
        }
        while (l2 != null) {
            int val = l2.val;
            if (moreThanTen) {
                val = val + 1;
                moreThanTen = false;
            }
            if (val > 9) {
                val = val - 10;
                moreThanTen = true;
            }
            ListNode l = new ListNode(val);
            current.next = l;
            current = l;
            l2 = l2.next;
        }
        if (moreThanTen) {
            ListNode l = new ListNode(1);
            current.next = l;
        }
        return pre.next != null ? pre.next : pre;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。