This commit is contained in:
fanxb 2021-12-26 23:04:24 +08:00
parent 05a05d3cec
commit e9f2979324
3 changed files with 122 additions and 1 deletions

View File

@ -0,0 +1,45 @@
package com.fanxb.common;
import java.util.HashMap;
import java.util.Map;
/**
* @author fanxb
* @date 2021年12月26日 22:02
*/
public class Q1 {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> numIndexMap = new HashMap<>(nums.length);
for (int i = 0; i < nums.length; i++) {
numIndexMap.put(nums[i], i);
}
int cur;
Integer targetIndex;
for (int i = 0; i < nums.length; i++) {
cur = nums[i];
targetIndex = numIndexMap.get(target - cur);
if (targetIndex != null && targetIndex > i) {
return new int[]{i, targetIndex};
}
}
return null;
}
/**
* 更优一次循环即可
*
* @return int[]
* @author fanxb
* @date 2021/12/26 22:08
*/
public int[] betterTwoSum(int[] nums, int target) {
Map<Integer, Integer> numIndexMap = new HashMap<>(nums.length);
for (int i = 0; i < nums.length; i++) {
if (numIndexMap.containsKey(target - nums[i])) {
return new int[]{numIndexMap.get(target - nums[i]), i};
}
numIndexMap.put(nums[i], i);
}
return null;
}
}

View File

@ -0,0 +1,20 @@
package com.fanxb.common;
import java.util.LinkedList;
/**
* @author fanxb
* @date 2021年12月26日 21:54
*/
public class Q1078 {
public String[] findOcurrences(String text, String first, String second) {
LinkedList<String> res = new LinkedList<>();
String[] strs = text.split(" ");
for (int i = 0; i < strs.length - 2; i++) {
if (strs[i].equals(first) && strs[i + 1].equals(second)) {
res.add(strs[i + 2]);
}
}
return res.toArray(new String[0]);
}
}

View File

@ -11,12 +11,68 @@ public class Q2 {
int val; int val;
ListNode next; ListNode next;
public ListNode() {
}
public ListNode(int val) { public ListNode(int val) {
this.val = val; this.val = val;
} }
} }
public static void main(String[] args) { public ListNode reverse(ListNode node) {
ListNode last = null, cur = node, next = node.next;
while (next != null) {
cur.next = last;
last = cur;
cur = next;
next = next.next;
}
cur.next = last;
return cur;
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
l1 = reverse(l1);
l2 = reverse(l2);
ListNode res = new ListNode(0), last = null, cur = res, next;
while (l1 != null || l2 != null) {
int val = cur.val;
if (l1 != null) {
val += l1.val;
l1 = l1.next;
}
if (l2 != null) {
val += l2.val;
l2 = l2.next;
}
if (val >= 10) {
cur.val = val - 10;
next = new ListNode(1);
} else {
cur.val = val;
next = new ListNode(0);
}
last = cur;
cur.next = next;
cur = next;
}
if (last != null && cur.val == 0) {
last.next = null;
}
return res;
}
public static void main(String[] args) {
ListNode l1 = new ListNode(2);
l1.next = new ListNode(4);
l1.next.next = new ListNode(9);
ListNode l2 = new ListNode(5);
l2.next = new ListNode(6);
l2.next.next = new ListNode(4);
l2.next.next.next = new ListNode(9);
new Q2().addTwoNumbers(l1, l2);
// new Q2().addTwoNumbers(new ListNode(0), new ListNode(0));
} }
} }