DW&LeetCode_day12(146、148、155)

DW&LeetCode_day12(146、148、155)


写在前面:

  • 俩题都不会写,先抄个题解理解一下,后面再改

开源内容

开源内容


 目录

DW&LeetCode_day12(146、148、155)

写在前面:

开源内容

学习大纲 

146. LRU 缓存机制

题解:

148. 排序链表

题解:

 155. 最小栈

题解:


学习大纲 


146. LRU 缓存机制

题解:

这题还不会,先抄个题解放着。

class LRUCache {
    private LinkedHashMap map;
    public LRUCache(int capacity) {
        map = new LinkedHashMap(capacity,0.75f,true){
            @Override
            public boolean removeEldestEntry(Map.Entry eldest) {
                return size() > capacity;
            }
        };
    }
    public int get(int key) {
        return map.getOrDefault(key,-1);
    }
    public void put(int key, int value) {
        map.put(key,value);
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */

DW&LeetCode_day12(146、148、155)_第1张图片

148. 排序链表

题解:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def sortList(self, head: ListNode) -> ListNode:
        def findMid(head):         # 找中心点,划分左右区域
            slow = head
            fast = head
            while fast.next and fast.next.next:  # 快慢指针判断条件
                fast = fast.next.next
                slow = slow.next
            return slow
        def merge(l,r):            #  有序链表的双路归并
            dummy = ListNode(None)
            p = dummy
            while l and r:
                if l.val <= r.val:
                    p.next = l
                    l = l.next
                else:
                    p.next = r
                    r = r.next
                p = p.next
            p.next = l or r
            return dummy.next
        if not head or not head.next:return head # 归并排序
        mid = findMid(head)
        left = head
        right = mid.next
        mid.next = None
        l = self.sortList(left)
        r = self.sortList(right)
        return merge(l,r)

DW&LeetCode_day12(146、148、155)_第2张图片

 155. 最小栈

题解:

class MinStack(object):

    def __init__(self):
        """
        initialize your data structure here.
        """
        #数据栈
        self.data = []
        #辅助栈
        self.helper = []

    def push(self, x):
        self.data.append(x)
        if len(self.helper) == 0 or x <= self.helper[-1]:
            self.helper.append(x)
        else:
            self.helper.append(self.helper[-1])

    def pop(self):
        if self.data:
            self.helper.pop()
            return self.data.pop()

    def top(self):
        if self.data:
            return self.data[-1]

    def getMin(self):
        if self.helper:
            return self.helper[-1]


# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()

DW&LeetCode_day12(146、148、155)_第3张图片

你可能感兴趣的:(LeetCode题解,Python,leetcode)