121. 买卖股票的最佳时机【简单】
https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
if(len < 2)
return 0;
int sell = 0;
int buy = -prices[0];
for (int i = 1; i < len; i++) {
sell = Math.max(sell, buy + prices[i]);
buy = Math.max(buy, -prices[i]); // 因为是负数,所以要找max,负得少的,就是当天价格低的。
}
return sell;
}
}
141. 环形链表【简单】
https://leetcode-cn.com/problems/linked-list-cycle/
快慢指针
循环的结束条件是重点,想清楚每种情况啥时候return。
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null)
return false;
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast)
return true;
}
return false;
}
}
160. 相交链表【简单】
https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode a = headA;
ListNode b = headB;
while (a != b) {
a = a == null ? headB : a.next;
b = b == null ? headA : b.next;
}
return a;
}
}
剑指 Offer 26. 树的子结构【中等】
https://leetcode-cn.com/problems/shu-de-zi-jie-gou-lcof/
递归判断
class Solution {
public boolean isSubStructure(TreeNode A, TreeNode B) {
if (A == null || B == null) return false;
return recur(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B);
}
private boolean recur(TreeNode A, TreeNode B) {
if (B == null) return true; // B走完了说明是子树
if (A == null || A.val != B.val) return false; //A走完了B不为空 || A值不等于B值
// 当A、B当前节点相等,还需要判断他们的左右子树的情况,so 递归
return recur(A.left, B.left) && recur(A.right, B.right);
}
}
102. 二叉树的层序遍历【中等】
https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
BFS迭代写法
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while (! queue.isEmpty()) {
List<Integer> level = new ArrayList<>();
int levelsize = queue.size();
for (int i = 0; i < levelsize; i++) {
TreeNode node = queue.poll();
level.add(node.val);
if (node.left != null)
queue.offer(node.left);
if (node.right != null)
queue.offer(node.right);
}
res.add(level);
}
return res;
}
}
DFS递归写法(可能会问到)
田字形的每一层(行)就对应一个 list,每次递归的时候都需要带一个index(表示当前的层数),也就对应那个田字格子中的第几行,如果当前行对应的 list 不存在,就加入一个空 list 进去。
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
dfs(0, root, res);
return res;
}
private void dfs (int index, TreeNode root, List<List<Integer>> res) {
//假设res是[ [1],[2,3] ], index是2,说明已经摸到底了,就再插入一个空list放到res中
if (res.size() == index)
res.add(new ArrayList<Integer>());
res.get(index).add(root.val); // 将现在所在节点的值加入res的对应列表中
if (root.left != null)
dfs(index+1, root.left, res);
if (root.right != null)
dfs(index+1, root.right, res);
}
}