DataWhale task 11

LRU 缓存机制

import java.util.LinkedHashMap;
import java.util.Map;

class LRUCache {

    private LRU cache;

    public LRUCache(int capacity) {
        this.cache = new LRU(capacity);
    }

    public int get(int key) {
        if (cache.containsKey(key)) {
            return cache.get(key);
        }
        return -1;
    }

    public void put(int key, int value) {
        cache.put(key, value);
    }

    class LRU extends LinkedHashMap {
        int capacity;

        public LRU(int capacity) {

            super(capacity, 0.75f, true);
            this.capacity = capacity;
        }

 
        @Override
        protected boolean removeEldestE***y(Map.E***y eldest) {
            return this.size() > capacity;
        }
    }
}

排序链表

class Solution {
    public ListNode sortList(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
        ListNode fast=head.next;
        ListNode slow=head;
        while(fast!=null&&fast.next!=null){
            fast=fast.next.next;
            slow=slow.next;
        }
        fast=slow.next;
        slow.next=null;
        head=sortList(head);        
        fast=sortList(fast);            
        return Merge(head,fast);
    }
    public ListNode Merge(ListNode l1,ListNode l2){
        ListNode pre=new ListNode(0);
        ListNode cur=pre;
        while(l1!=null&&l2!=null){
            if(l1.val

最小栈

class MinStack {
    ListNode l1=null;
    ListNode head=null;
    ListNode l2=null;
    public MinStack() {

    }

    public void push(int x) {
       if(l1==null){
           l1=new ListNode(x);
           head=l1;
       }else{
           l1.next=new ListNode(x);
           l1.next.prev=l1;
           l1=l1.next;
       }
    }

    public void pop() {
          if(l1.prev!=null){

        l1=l1.prev;
        l1.next=null;
        }else{
            l1=null;
        }
    }

    public int top() {
      return l1.val;
    }

    public int getMin() {
        int min=head.val;
        l2=head;
        while(l2.next!=null){
            l2=l2.next;
            if(l2.val

你可能感兴趣的:(DataWhale task 11)