力扣高频|算法面试题汇总(六):哈希与映射

力扣高频|算法面试题汇总(一):开始之前
力扣高频|算法面试题汇总(二):字符串
力扣高频|算法面试题汇总(三):数组
力扣高频|算法面试题汇总(四):堆、栈与队列
力扣高频|算法面试题汇总(五):链表
力扣高频|算法面试题汇总(六):哈希与映射
力扣高频|算法面试题汇总(七):树
力扣高频|算法面试题汇总(八):排序与检索
力扣高频|算法面试题汇总(九):动态规划
力扣高频|算法面试题汇总(十):图论
力扣高频|算法面试题汇总(十一):数学&位运算

力扣高频|算法面试题汇总(六):哈希与映射

力扣链接
目录:

  • 1.Excel表列序号
  • 2.四数相加 II
  • 3.常数时间插入、删除和获取随机元素

1.Excel表列序号

给定一个Excel表格中的列名称,返回其相应的列序号。
例如,
A -> 1
B -> 2
C -> 3

Z -> 26
AA -> 27
AB -> 28

示例 1:
输入: “A”
输出: 1
示例 2:
输入: “AB”
输出: 28

思路
就是一个26进制转10进制。
C++

class Solution {
public:
    int titleToNumber(string s) {
        // 26进制转10进制
        int num = 0;
        for(int i = 0; i < s.length(); ++i){
            num = num * 26 + (s[i] - 'A' + 1);  
        }
        return num;
    }
};

Python

class Solution:
    def titleToNumber(self, s: str) -> int:
        num = 0
        for i in range(len(s)):
            num = num*26 + (ord(s[i]) - ord('A') + 1)
        return num

2.四数相加 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

思路
纯暴力时间复杂度为 O ( n 4 ) O(n^4) O(n4)。构建哈希表,时间复杂度为 O ( n 2 ) O(n^2) O(n2)
由于满足条件: A [ i ] + B [ j ] + C [ k ] + D [ l ] = 0 A[i] + B[j] + C[k] + D[l] = 0 A[i]+B[j]+C[k]+D[l]=0,所以可以得到等式: A [ i ] + B [ j ] = − ( C [ k ] + D [ l ] ) A[i] + B[j] = - (C[k] + D[l]) A[i]+B[j]=(C[k]+D[l])。也就是先计算数组A和数组B的和,构建哈希表,键为数组A和数组B的和,值为该和出现的次数。第一步计算数组C和数组D和,取负数,如果在哈希表中,则输出的结果加该哈希表的值。
C++

class Solution {
public:
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
        map<int, int> sumHash;
        // 先计算A+B的值
        for(auto a : A)
            for(auto b : B){
                if(sumHash.find(a + b) == sumHash.end())
                    sumHash[a + b] = 1;
                else
                    ++sumHash[a + b];
            }
        int res = 0;
        // 计算C+D的值
        for(auto c : C)
            for(auto d : D)
            {
                if(sumHash.find(-c - d) != sumHash.end()){
                    res += sumHash[-c-d];
                }
            }
        return res;
    }
};

Python

class Solution:
    def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
        sumHash = {}
        res = 0
        for a in A:
            for b in B:
                if not (a + b) in sumHash:
                    sumHash[a + b] = 1
                else:
                    sumHash[a + b] += 1
        for c in C:
            for d in D:
                if (-c -d) in sumHash:
                    res += sumHash[-c -d]
        return res

3.常数时间插入、删除和获取随机元素

设计一个支持在平均 时间复杂度 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();

思路
参考方法:使用哈希表存储数组的索引
很巧妙的一个点:如何在 O ( 1 ) O(1) O(1)删除?虽然你通过哈希表已经找到了这个元素,但是如果他在数组的中间?你要删除不调用erase函数,这样使得整个数组的位置都发生了错乱,并且不是一个 O ( 1 ) O(1) O(1)的操作。

接近办法:不需要从中把他删除,直接把找到的元素a给置换到数组的最后一位,然后pop_back就是 O ( 1 ) O(1) O(1)了,这里不用真正的交换,因为本来就要删除,直接把元素赋值就可以,然后更新一下原来最后一位的哈希表位置就可以了。
C++

class RandomizedSet {
private:
    map<int, int> idHash;
    vector<int> num;
public:
    /** Initialize your data structure here. */
    RandomizedSet() {

    }
    
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    bool insert(int val) {
        if(idHash.find(val) == idHash.end()){
            // 添加元素
            num.push_back(val);
            int index = num.size() - 1;
            idHash[val] = index;
            return true;
        }else{
            return false;
        }
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    bool remove(int val) {
        auto itear = idHash.find(val);
        if(itear != idHash.end()){
            int index = itear->second;
            // 替换需要删除的元素
            num[index] = num.back();
            // 修改对应的索引
            idHash[num.back()] = index;
            // 删除已经复制过的元素
            num.pop_back();
            idHash.erase(itear);
            return true;
        }else
            return false;
    }
    
    /** Get a random element from the set. */
    int getRandom() {
        if(num.size() == 0) return -1;
        int index = rand() % num.size();
        return num[index];
    }
};

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet* obj = new RandomizedSet();
 * bool param_1 = obj->insert(val);
 * bool param_2 = obj->remove(val);
 * int param_3 = obj->getRandom();
 */

Python:

class RandomizedSet:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.num = []
        self.idHash = {}

    def insert(self, val: int) -> bool:
        """
        Inserts a value to the set. Returns true if the set did not already contain the specified element.
        """
        if not val in self.idHash:
            self.num.append(val)
            index = len(self.num) - 1
            self.idHash[val] = index
            return True
        else:
            return False

    def remove(self, val: int) -> bool:
        """
        Removes a value from the set. Returns true if the set contained the specified element.
        """
        if val in self.idHash:
            index = self.idHash[val]
            # 替换
            self.num[index] = self.num[-1]
            # 修改索引
            self.idHash[self.num[-1]] = index
            # 删除
            self.num.pop()
            # 删除索引
            self.idHash.pop(val)
            return True
        else:
            return False

    def getRandom(self) -> int:
        """
        Get a random element from the set.
        """
        if len(self.num) == 0:
            return -1
        index = random.randint(0,len(self.num) - 1)
        return self.num[index]


# 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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值