共计 1881 个字符,预计需要花费 5 分钟才能阅读完成。
1. 两数之和
给定一个整数数组 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}; | |
} |
2. 两数相加
给出两个 非空 的链表用来示意两个非负的整数。其中,它们各自的位数是依照 逆序 的形式存储的,并且它们的每个节点只能存储 一位 数字。
如果,咱们将这两个数相加起来,则会返回一个新的链表来示意它们的和。
您能够假如除了数字 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; | |
} |
3. 无反复字符的最长子串
给定一个字符串,请你找出其中不含有反复字符的 最长子串 的长度。
public int lengthOfLongestSubstring(String s) {}
7. 整数反转
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; | |
} |
8. 字符串转换整数 (atoi)
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; | |
} |
9. 回文数
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; | |
} |
正文完