[LeetCode] Shortest Word Distance
2015-08-05 16:02
281 查看
Problem Description:
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
For example,
Assume that words =
Given word1 =
Given word1 =
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
The naive idea is very easy. But could you solve it in one-pass? Well, the one-pass code (taken from here) is rewritten in C++ as follows.
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
For example,
Assume that words =
["practice", "makes", "perfect", "coding", "makes"].
Given word1 =
"coding", word2 =
"practice", return 3.
Given word1 =
"makes", word2 =
"coding", return 1.
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
The naive idea is very easy. But could you solve it in one-pass? Well, the one-pass code (taken from here) is rewritten in C++ as follows.
class Solution { public: int shortestDistance(vector<string>& words, string word1, string word2) { int n = words.size(), idx1 = -1, idx2 = -1, dist = INT_MAX; for (int i = 0; i < n; i++) { if (words[i] == word1) idx1 = i; else if (words[i] == word2) idx2 = i; if (idx1 != -1 && idx2 != -1) dist = min(dist, abs(idx1 - idx2)); } return dist; } };
相关文章推荐
- 编译boost
- php为图片添加水印
- 设置secureCRT中vim的字体颜色
- leetcode 74: Search a 2D Matrix
- Multiplying by Rotation
- 关于在Windows7 64位操作系统下,读取system32下的文件失败,提示“系统找不到指定文件”。
- Multiplying by Rotation
- Android adb的一些使用方法
- Codeforces 115A- Party
- python eval函数 动态执行python语句
- python中的字典详细介绍
- bundle install 老是中断,可以在gemfile里面把source换成taobao源,可以自动安装
- 上拉页面自动加载
- 全民消消乐电信SDK对接
- Linux IO实时监控iostat命令详解
- 学习日记8.5
- 关于命令行参数
- 生成framework ,脚本
- 求位数 hdu 1018 Big Number
- android 读取本地大图片时防止oom方法