LeetCode 599. Minimum Index Sum of Two Lists

题意:找出两个人都喜欢的餐厅,返回序号之和最小的。

solution:hash记录餐馆名对应的序号之和。遍历第一个数组时,记录每一个餐厅的序号,遍历第二个数组时,仅处理在1中出现过的餐厅。

class Solution {
public:
    vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
        // 对于所有count==2的,记录最小index sum如果有更小则 清空+插入 如果相等 则仅插入
        // 1. hash
        /*unordered_map<string, vector<int>> hash; // name-(count,index sum)
        int min_index = 2000;
        vector<string> res;        
        for ( int i = 0; i < list1.size(); i++ ) {
            hash[list1[i]].push_back(1);
            hash[list1[i]].push_back(i);
        }
        for ( int i = 0; i < list2.size(); i++ ) {
            if ( hash.find(list2[i]) != hash.end() ) {
                hash[list2[i]][0]++;
                hash[list2[i]][1]+=i;                
            }
        }
        for ( auto n : hash ) {
            if ( n.second[0] == 2 ) {
                if ( n.second[1] < min_index ) {
                    res.clear();
                    res.push_back(n.first);
                    min_index = n.second[1];
                }
                else if ( n.second[1] == min_index )
                    res.push_back(n.first);
            }
        }*/
        
        // 1.5 clever hash
        unordered_map<string, int> hash; // name-index sum
        vector<string> res;
        int min_sum = 2000;
        
        for ( int i = 0; i < list1.size(); i++ ) {
            hash[list1[i]] = i;
        }
        for ( int i = 0; i < list2.size(); i++ ) {
            if ( hash.find(list2[i]) != hash.end() ) {
                if ( hash[list2[i]]+i <= min_sum ) {
                    if ( hash[list2[i]]+i < min_sum ) {
                        min_sum = hash[list2[i]]+i;
                        res.clear();                        
                    }
                    res.push_back(list2[i]);
                }
            }
        }
        return res;
    }
};

submission:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值