LC2. 两数相加
注:和LC415的字符串相加的题目换汤不换药,保存一个变量进制位,两数的总和是两个数加上一个进制位,最后还需要判断一下进制位是否为1添加到末尾
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
//进制位
int carry = 0;
while(l1 != null || l2 != null){
int x = l1 == null ? 0 : l1.val;
int y = l2 == null ? 0 : l2.val;
int sum = x + y + carry;
carry = sum / 10;
sum = sum % 10;
cur.next = new ListNode(sum);
cur = cur.next;
if(l1 != null) l1 = l1.next;
if(l2 != null) l2 = l2.next;
}
if(carry == 1)
cur.next = new ListNode(carry);
return dummy.next;
}
}
LC104. 二叉树的最大深度
注:递归左右深度最后返回左右较大值加上root节点的1就是最大深度
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root == null)
return 0;
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left,right) + 1;
}
}
LC151. 翻转字符串里的单词
//对API的熟悉以及调用
class Solution {
public String reverseWords(String s) {
s = s.trim();
List<String> list = Arrays.asList(s.split("\\s+"));
Collections.reverse(list);
return String.join(" ",list);
}
}