Skip to content

Commit 1f8194e

Browse files
committed
added test
1 parent 253ad89 commit 1f8194e

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

src/main/java/com/fishercoder/solutions/_1.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.fishercoder.solutions;
22

3+
import java.util.Arrays;
34
import java.util.HashMap;
45
import java.util.Map;
56

@@ -29,4 +30,27 @@ public int[] twoSum(int[] nums, int target) {
2930
}
3031
}
3132

33+
public static class Solution2 {
34+
public int[] twoSum(int[] nums, int target) {
35+
Map<Integer, Integer> hm = new HashMap<>();
36+
int len = nums.length;
37+
for (int i = 0; i < len; i++) {
38+
int diff = target - nums[i];
39+
if (hm.containsKey(diff)) {
40+
return new int[]{hm.get(diff), i};
41+
} else {
42+
hm.put(nums[i], i);
43+
}
44+
}
45+
return new int[]{-1, -1};
46+
}
47+
}
48+
49+
public static void main(String[] args) {
50+
int[] array = new int[] {2, 7, 11, 16};
51+
int target = 9;
52+
System.out.println(Arrays.toString(new Solution1().twoSum(array, target)));
53+
System.out.println(Arrays.toString(new Solution2().twoSum(array, target)));
54+
}
55+
3256
}

src/main/java/com/fishercoder/solutions/_2.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import com.fishercoder.common.classes.ListNode;
44

5+
import java.util.List;
6+
57
/**
68
* 2. Add Two Numbers
79
@@ -39,4 +41,31 @@ public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
3941
}
4042
}
4143

44+
public static class Solution2 {
45+
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
46+
ListNode c1 = l1;
47+
ListNode c2 = l2;
48+
ListNode c3 = new ListNode(0);
49+
ListNode head = c3;
50+
int carry = 0;
51+
while(c1 != null || c2 != null) {
52+
if(c1 != null) {
53+
carry += c1.val;
54+
c1 = c1.next;
55+
}
56+
if(c2 != null) {
57+
carry += c2.val;
58+
c2 = c2.next;
59+
}
60+
c3.next = new ListNode(carry % 10);
61+
carry = carry / 10;
62+
c3 = c3.next;
63+
}
64+
if (carry == 1)
65+
c3.next = new ListNode(1);//this means there's a carry, so we add additional 1, e.g. [5] + [5] = [0, 1]
66+
67+
return head.val == 0 ? head.next : head;
68+
}
69+
}
70+
4271
}

0 commit comments

Comments
 (0)