[LC] 243. Shortest Word Distance
Posted xuanlu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LC] 243. Shortest Word Distance相关的知识,希望对你有一定的参考价值。
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
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.
Solution1:
O(N^2)
class Solution { public int shortestDistance(String[] words, String word1, String word2) { int res = words.length; for (int i = 0; i < words.length; i++) { if (words[i].equals(word1)) { for (int j = 0; j < words.length; j++) { if (words[j].equals(word2)) { res = Math.min(res, Math.abs(i - j)); } } } } return res; } }
Solution2:
O(N)
class Solution { public int shortestDistance(String[] words, String word1, String word2) { int res = words.length; int s1 = -1, s2 = -1; for (int i = 0; i < words.length; i++) { String cur = words[i]; if (cur.equals(word1)) { s1 = i; } else if (cur.equals(word2)) { s2 = i; } if (s1 != -1 && s2 != -1) { res = Math.min(res, Math.abs(s1 - s2)); } } return res; } }
以上是关于[LC] 243. Shortest Word Distance的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 243. Shortest Word Distance 最短单词距离
lc 862. Shortest Subarray with Sum at Least K
245. Shortest Word Distance III 单词可以重复的最短单词距离