给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
int num = target - nums[i];
if(map.containsKey(num)) {
return new int[]{map.get(num), i};
}
map.put(nums[i], i);
}
return new int[]{-1, -1};
}
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode p = l1, q = l2, cur = dummy;
int carry = 0;
while(p != null || q != null) {
int x = p != null ? p.val : 0;
int y = q != null ? q.val : 0;
int sum = x + y + carry;
carry = sum/10;
cur.next = new ListNode(sum%10);
cur = cur.next;
if(p != null) {
p = p.next;
}
if(q != null) {
q = q.next;
}
}
if(carry > 0) {
cur.next = new ListNode(carry);
}
return dummy.next;
}
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
public int lengthOfLongestSubstring(String s) {
}
public int reverse(int x) {
int res = 0;
while(x != 0) {
int pop = x % 10;
x = x/10;
if(res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE && pop > 7)) {
return 0;
}
if(res < Integer.MIN_VALUE/10 || (res == Integer.MIN_VALUE && pop < -8)) {
return 0;
}
res = res * 10 + pop;
}
return res;
}
public int myAtoi(String str) {
if(str == null || str.length() == 0) {
return 0;
}
int idx = 0;
int len = str.length();
while(idx < len && str.charAt(idx) == ' ') {
idx++;
}
if(idx == len) {
return 0;
}
boolean negative = false;
if(str.charAt(idx) == '-') {
negative = true;
idx++;
} else if(str.charAt(idx) == '+') {
idx++;
} else if(!Character.isDigit(str.charAt(idx))) {
return 0;
}
int res = 0;
while(idx < len && Character.isDigit(str.charAt(idx))) {
int digit = str.charAt(idx) - '0';
if(res > (Integer.MAX_VALUE - digit) / 10) {
return negative ? Integer.MIN_VALUE:Integer.MAX_VALUE;
}
res = res * 10 + digit;
idx++;
}
return negative? -res:res;
}
public boolean isPalindrome(int x) {
if(x < 0 || (x != 0 && x%10 ==0)) {
return false;
}
int revertNum = 0;
while(x > revertNum) {
revertNum = revertNum*10 + x%10;
x /=10;
}
return x == revertNum || x == revertNum /10;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。