if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
if (l1.val <= l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}
HIGH.12 合并K 个排序链表
思路巨简单,难得一次都不用调试!!!循环直接搞定,什么分治大法我不懂!
用容量为K的最小堆优先队列,把链表的头结点都放进去,然后出队当前优先队列中最小的,挂上链表,,然后让出队的那个节点的下一个入队,再出队当前优先队列中最小的,直到优先队列为空。
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists.length == 0) {
return null;
}
ListNode dummyHead = new ListNode(0);
ListNode curr = dummyHead;
PriorityQueue pq = new PriorityQueue<>(new Comparator() {
@Override
public int compare(ListNode o1, ListNode o2) {
return o1.val - o2.val;
}
});
for (ListNode list : lists) {
if (list == null) {
continue;
}
pq.add(list);
}
while (!pq.isEmpty()) {
ListNode nextNode = pq.poll();
curr.next = nextNode;
curr = curr.next;
if (nextNode.next != null) {
pq.add(nextNode.next);
}
}
return dummyHead.next;
}
}
HIGH.13 买卖股票的最佳时机
思路还是挺清晰的,还是DP思想:
记录【今天之前买入的最小值】
计算【今天之前最小值买入,今天卖出的获利】,也即【今天卖出的最大获利】
比较【每天的最大获利】,取最大值即可
class Solution {
public int maxProfit(int[] prices) {
if(prices.length <= 1)
return 0;
int min = prices[0], max = 0;
for(int i = 1; i < prices.length; i++) {
max = Math.max(max, prices[i] - min);
min = Math.min(min, prices[i]);
}
return max;
}
}
HIGH.14 买卖股票的最佳时机II
算法题(×) 脑筋急转弯题( √ )
扫描一遍 只要后一天比前一天大 就把这两天的差值加一下
class Solution {
public int maxProfit(int[] prices) {
int ans=0;
for(int i=1;i<=prices.length-1;i++)
{
if(prices[i]>prices[i-1])
{
ans+=prices[i]-prices[i-1];
}
}
return ans;
}
}
HIGH.15 最大子序和
class Solution {
public int maxSubArray(int[] nums) {
int res = nums[0];
int sum = 0;
for (int num : nums) {
if (sum > 0)
sum += num;
else
sum = num;
res = Math.max(res, sum);
}
return res;
}
}
HIGH.16 最小栈
class MinStack {
private Node head;
public void push(int x) {
if(head == null)
head = new Node(x, x);
else
head = new Node(x, Math.min(x, head.min), head);
}
public void pop() {
head = head.next;
}
public int top() {
return head.val;
}
public int getMin() {
return head.min;
}
private class Node {
int val;
int min;
Node next;
private Node(int val, int min) {
this(val, min, null);
}
private Node(int val, int min, Node next) {
this.val = val;
this.min = min;
this.next = next;
}
}
}
HIGH.17 LRU 缓存机制
class LRUCache {
private int cap;
private Map<Integer, Integer> map = new LinkedHashMap<>(); // 保持插入顺序
public LRUCache(int capacity) {
this.cap = capacity;
}
public int get(int key) {
if (map.keySet().contains(key)) {
int value = map.get(key);
map.remove(key);
// 保证每次查询后,都在末尾
map.put(key, value);
return value;
}
return -1;
}
public void put(int key, int value) {
if (map.keySet().contains(key)) {
map.remove(key);
} else if (map.size() == cap) {
Iterator<Map.Ey<Integer, Integer>> iterator = map.eySet().iterator();
iterator.next();
iterator.remove();
// int firstKey = map.e***ySet().iterator().next().getValue();
// map.remove(firstKey);
}
map.put(key, value);
}
}