发布时间:2023-03-27 15:30
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
package toplikedquestions;
import java.util.HashMap;
public class Problem_0001_TwoSum {
public static int[] twoSum(int[] nums, int target) {
HashMap map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
return new int[] { map.get(target - nums[i]), i };
}
map.put(nums[i], i);
}
return new int[] { -1, -1 };
}
}
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
package toplikedquestions;
public class Problem_0002_AddTwoNumbers {
public static class ListNode {
public int val;
public ListNode next;
public ListNode(int value) {
this.val = value;
}
}
public static ListNode addTwoNumbers(ListNode head1, ListNode head2) {
int ca = 0;
int n1 = 0;
int n2 = 0;
int n = 0;
ListNode c1 = head1;
ListNode c2 = head2;
ListNode node = null;
ListNode pre = null;
while (c1 != null || c2 != null) {
n1 = c1 != null ? c1.val : 0;
n2 = c2 != null ? c2.val : 0;
n = n1 + n2 + ca;
pre = node;
node = new ListNode(n % 10);
node.next = pre;
ca = n / 10;
c1 = c1 != null ? c1.next : null;
c2 = c2 != null ? c2.next : null;
}
if (ca == 1) {
pre = node;
node = new ListNode(1);
node.next = pre;
}
return reverseList(node);
}
public static ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}
package toplikedquestions;
public class Problem_0003_LongestSubstringWithoutRepeatingCharacters {
public static int lengthOfLongestSubstring(String str) {
if (str == null || str.equals("")) {
return 0;
}
char[] chas = str.toCharArray();
int[] map = new int[256];
for (int i = 0; i < 256; i++) {
map[i] = -1;
}
int len = 0;
int pre = -1;
int cur = 0;
for (int i = 0; i != chas.length; i++) {
pre = Math.max(pre, map[chas[i]]);
cur = i - pre;
len = Math.max(len, cur);
map[chas[i]] = i;
}
return len;
}
}