zoukankan      html  css  js  c++  java
  • LC 244. Shortest Word Distance II 【lock, Medium】

    Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many times with different parameters. 

    Example:
    Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

    Input: word1 = “coding”, word2 = “practice”
    Output: 3
    
    Input: word1 = "makes", word2 = "coding"
    Output: 1

    Note:
    You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

    利用一个字典记录所有相同的字母的位置,然后就是两个有序数组比较最近的元素。

    我设想把一个数组插入另一个数组,然后比较。C++ lower_bound大法。

    class WordDistance {
    private:
        unordered_map<string,vector<int>> map;
    public:
        WordDistance(vector<string> words) {
          for(int i=0; i<words.size(); i++) map[words[i]].push_back(i);
        }
        
        int shortest(string word1, string word2) {
          vector<int> l1 = map[word1];
          vector<int> l2 = map[word2];
          int idx = 0;
          int ret = INT_MAX;
          for(int i=0; i<l2.size(); i++){
            idx = lower_bound(l1.begin(), l1.end(),l2[i]) - l1.begin();
            if(idx == l1.size()){
              ret = min(ret, l2[i] - l1.back());
            }else if(idx == 0){
              ret = min(ret, abs(l2[i] - l1.front()));
            }else{
              ret = min(ret, abs(l2[i] - l1[idx]));
              ret = min(ret, abs(l2[i] - l1[idx-1]));
            }
            if(ret == 0) return 0;
          }
          return ret;
        }
    };

    下面是网上的简单做法,思路差不多,找最小的时候遍历,结果runtime24ms...

    class WordDistance {
    public:
        unordered_map<string, vector<int> > map;
        WordDistance(vector<string> words) {
            for(int i = 0; i < words.size(); i++){
                map[words[i]].push_back(i);
            }
        }
        int shortest(string word1, string word2) {
            vector<int> v1, v2;
            v1 = map[word1];
            v2 = map[word2];
            int diff = INT_MAX;
            for(int i = 0; i < v1.size(); i++)
                for(int j = 0; j < v2.size(); j++)
                    if(abs(v1[i]-v2[j]) < diff)
                        diff = abs(v1[i]-v2[j]);
            return diff;
        }
    };
  • 相关阅读:
    高并发下缓存失效问题及解决方案
    行为型设计模式
    Redisson
    行为型设计模式
    Docker 安装 Elasticsearch 和 Kibana
    行为型设计模式
    C# 使用 WebBrowser 实现 HTML 转图片功能
    .NET 程序下锐浪报表 (Grid++ Report) 的绿色发布指南
    .NET 程序员的 Playground :LINQPad
    Windows 服务器上的 WordPress 站点优化笔记
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10141026.html
Copyright © 2011-2022 走看看