力扣Hot100每日N题(9~10)

207. 课程表

拓扑排序模板

/*
Deque queue = new LinkedList<>();
boolean u = queue.offerLast(i);
int u = queue.peekLast(i);
int u = queue.pollFirst();
*/
class Solution {
    private int[] inNum;
    private List<List<Integer>> graph;
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        inNum = new int[numCourses];
        graph = new ArrayList<>();
        for(int i = 0; i < numCourses; i++){
            graph.add(new ArrayList<>());
        }
        for(int[] prerequisite : prerequisites){
            int v = prerequisite[0], u = prerequisite[1];
            graph.get(u).add(v);
            inNum[v]++;
        }
        Deque<Integer> queue = new LinkedList<>();
        int num = 0;
        for(int i = 0; i < numCourses; i++){
            if(inNum[i] == 0){
                queue.offerLast(i);
                num++;
            }
        }
        while(!queue.isEmpty()){
            int u = queue.pollFirst();
            List<Integer> next = graph.get(u);
            for(int v : next){
                if(--inNum[v] == 0){
                    num++;
                    queue.offerLast(v);
                }

            }
        }
        return num == numCourses;
    }
}

206. 反转链表

递归or迭代

/**
 * 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 reverseList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
    public ListNode reverseList(ListNode head) {
        ListNode pre = null, suf;
        while(head != null){
            suf = head.next;
            head.next = pre;
            pre = head;
            head = suf;
        }
        return pre;
    }
}

你可能感兴趣的:(leetcode,算法,职场和发展)