Leetcode--哈希、映射(python)

Excel表列序號

給定一個Excel表格中的列名稱,返回其相應的列序號。

例如,

A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28 
...

示例 1:

輸入: “A”
輸出: 1
示例 2:

輸入: “AB”
輸出: 28
示例 3:

輸入: “ZY”
輸出: 701

解法
其實就是把十進制改成了26進制。
注意把字符轉換成整數的方法:ord()
以及’A’的整數值是65

class Solution(object):
    def titleToNumber(self, s):
        """
        :type s: str
        :rtype: int
        """
        res = 0
        for idx in range(len(s)):
            res = res * 26 + (ord(s[idx]) - ord('A') + 1)
            
        return res

四數相加 II

給定四個包含整數的數組列表 A , B , C , D ,計算有多少個元組 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0。

爲了使問題簡單化,所有的 A, B, C, D 具有相同的長度 N,且 0 ≤ N ≤ 500 。所有整數的範圍在 -228 到 228 - 1 之間,最終結果不會超過 231 - 1 。

例如:

輸入:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]

輸出:
2

解釋:
兩個元組如下:

  1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
  2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

解法
本來以爲會有比兩次循環更簡單點的解法的,但是並沒有找到。
用一個存儲前兩個的每個結果出現的次數就可以了,不需要存儲index。

class Solution(object):
    def fourSumCount(self, A, B, C, D):
        """
        :type A: List[int]
        :type B: List[int]
        :type C: List[int]
        :type D: List[int]
        :rtype: int
        """
        
        dic = {}
        res = 0
        for i in range(len(A)):
            for j in range(len(B)):
                tmp = A[i] + B[j]
                if tmp not in dic:
                    dic[tmp] = 1
                else:
                    dic[tmp] += 1
                
        for i in range(len(C)):
            for j in range(len(D)):
                tmp = C[i] + D[j]
                if -tmp in dic:
                    res += dic[-tmp]
                
        return res
        

常數時間插入、刪除和獲取隨機元素

設計一個支持在平均 時間複雜度 O(1) 下,執行以下操作的數據結構。

insert(val):當元素 val 不存在時,向集合中插入該項。
remove(val):元素 val 存在時,從集合中移除該項。
getRandom:隨機返回現有集合中的一項。每個元素應該有相同的概率被返回。
示例 :

// 初始化一個空的集合。
RandomizedSet randomSet = new RandomizedSet();

// 向集合中插入 1 。返回 true 表示 1 被成功地插入。
randomSet.insert(1);

// 返回 false ,表示集合中不存在 2 。
randomSet.remove(2);

// 向集合中插入 2 。返回 true 。集合現在包含 [1,2] 。
randomSet.insert(2);

// getRandom 應隨機返回 1 或 2 。
randomSet.getRandom();

// 從集合中移除 1 ,返回 true 。集合現在包含 [2] 。
randomSet.remove(1);

// 2 已在集合中,所以返回 false 。
randomSet.insert(2);

// 由於 2 是集合中唯一的數字,getRandom 總是返回 2 。
randomSet.getRandom();

解法
考察比較基礎的一些用法,注意獲得random的值的方法是在總長度中隨機找一個index。
以及random.randint(l,r)的左右都能取到

import random


class RandomizedSet(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.randSet = []
        

    def insert(self, val):
        """
        Inserts a value to the set. Returns true if the set did not already contain the specified element.
        :type val: int
        :rtype: bool
        """
        if val not in self.randSet:
            self.randSet.append(val)
            return True
        else:
            return False
        

    def remove(self, val):
        """
        Removes a value from the set. Returns true if the set contained the specified element.
        :type val: int
        :rtype: bool
        """
        if val in self.randSet:
            self.randSet.remove(val)
            return True
        else:
            return False
        

    def getRandom(self):
        """
        Get a random element from the set.
        :rtype: int
        """
        l = len(self.randSet)
        rand = random.randint(0, l-1)
        return self.randSet[rand]
        


# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()

LRU緩存機制

運用你所掌握的數據結構,設計和實現一個 LRU (最近最少使用) 緩存機制。它應該支持以下操作: 獲取數據 get 和 寫入數據 put 。

獲取數據 get(key) - 如果密鑰 (key) 存在於緩存中,則獲取密鑰的值(總是正數),否則返回 -1。
寫入數據 put(key, value) - 如果密鑰不存在,則寫入其數據值。當緩存容量達到上限時,它應該在寫入新數據之前刪除最近最少使用的數據值,從而爲新的數據值留出空間。

進階:

你是否可以在 O(1) 時間複雜度內完成這兩種操作?

示例:

LRUCache cache = new LRUCache( 2 /* 緩存容量 */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 該操作會使得密鑰 2 作廢
cache.get(2); // 返回 -1 (未找到)
cache.put(4, 4); // 該操作會使得密鑰 1 作廢
cache.get(1); // 返回 -1 (未找到)
cache.get(3); // 返回 3
cache.get(4); // 返回 4

解法
實際上是考察python3中字典的用法,首先題目要存儲key和value,也就是想到用字典;其次,需要在線性時間內實現三種情況:

  • 查找item
  • 當前被查找的數被挪到最後面的位置(先pop,再添加進去)
  • 刪除最前面的值(轉換成list,得到第一個位置再pop)
class LRUCache:
 
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.cache = {}
        
 
    def get(self, key: int) -> int:
        if key not in self.cache:
            return -1
        self.cache[key] = self.cache.pop(key)
        return self.cache[key]
        
 
    def put(self, key: int, value: int) -> None:
        if key in self.cache:
            self.cache.pop(key)
        self.cache[key] = value
        if len(self.cache) > self.capacity:
            x = list(self.cache)[0]
            self.cache.pop(x)
        


# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
發佈了150 篇原創文章 · 獲贊 24 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章