-
两数之和
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;
}
}
-
两数之和
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;
}
}