Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

A variation of linear scan..

typedef pair<int, bool> Rec;
class Solution {
public:
    int shortestDistance(vector<string>& words, string word1, string word2)     {
        vector<Rec> recs;

        int ret = INT_MAX;
        for (int i = 0; i < words.size(); i++)
        {
            bool bFound = false;
            if (words[i] == word1){
                bFound = true;
                recs.push_back(Rec(i, true));
            }
            if (words[i] == word2){
                bFound = true;
                recs.push_back(Rec(i, false));
            }
            if (bFound)
            {
                size_t len = recs.size();
                if (recs.size() > 1)
                {
                    if (recs[len - 1].second != recs[len - 2].second)
                    {
                        int cur = recs[len - 1].first - recs[len - 2].first;
                        ret = std::min(cur, ret);
                    }
                }
            }
        }
        return ret;
    }
};
posted on 2015-08-20 15:32  Tonix  阅读(135)  评论(0)    收藏  举报