875. 爱吃香蕉的珂珂 / 剑指 Offer II 077. 链表排序

875. 爱吃香蕉的珂珂【中等题】【每日一题】

思路:【二分模拟】

这题4号刚写过,思路就不再记录了。
剑指 Offer II 073. 狒狒吃香蕉

代码:

class Solution {
    public int minEatingSpeed(int[] piles, int h) {
        int max = 0;
        for (int pile : piles) {
            max = Math.max(max,pile);
        }
        int left = 1,right = max;
        while (left <= right){
            int k = left + ((right - left) >> 1);
            int remain = h;
            for (int pile : piles) {
                remain -= pile / k;
                if (pile % k != 0){
                    remain--;
                }
            }
            if (remain < 0){//k小了 警卫回来的时候还没吃完
                left = k + 1;
            }else {//k大了,警卫还没回来就吃完了
                right = k - 1;
            }
        }
        return left;
    }
}

剑指 Offer II 077. 链表排序【中等题】

思路:

题解用自底向上归并排序。
这里选择调用sort。

代码:

/**
 * 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 sortList(ListNode head) {
        List<Integer> list = new ArrayList<>();
        while (head != null){
            list.add(head.val);
            head = head.next;
        }
        Collections.sort(list);
        ListNode root = new ListNode(0);
        ListNode node = root;
        for (Integer val : list) {
            node.next = new ListNode(val);
            node = node.next;
        }
        return root.next;
    }
}

你可能感兴趣的:(力扣刷题记录,链表,数据结构,leetcode,java,刷题记录)