Leetcode solution 243: Shortest Word Distance

Posted baozitraining

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode solution 243: Shortest Word Distance相关的知识,希望对你有一定的参考价值。

 

Problem Statement 

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.

 Problem link

Video Tutorial

You can find the detailed video tutorial here

Thought Process

It is a bit confusing at first to be confused with the "Edit Distance" problem. However, there are duplicate words in the array, it‘s just a matter of finding the minimum distance between two words, where words could be found in multiple places in the array.

 

Brute force way (for each word, find the closest distance with the other word) would give you O(N^2) time complexity where N is the array size. An O(N) optimization would be having two indices for each word and keep updating the minimum distance. It is greedy because the closer the two elements are, the smaller the distance would be.

 

You can refer to Leetcode official solution for a detailed explanation.

Solutions

 1 public int shortestDistance(String[] words, String word1, String word2) {
 2     if (words == null || words.length == 0 || word1 == null || word2 == null || word1.equals(word2)) {
 3         return -1;
 4     }
 5     int minDistance = words.length;
 6 
 7     int wordIndex1 = -1;
 8     int wordIndex2 = -1;
 9 
10     for (int i = 0; i < words.length; i++) {
11         if (words[i].equals(word1)) {
12             wordIndex1 = i;
13             if (wordIndex2 != -1) {
14                 minDistance = Math.min(minDistance, Math.abs(wordIndex1 - wordIndex2));
15             }
16         }
17         if (words[i].equals(word2)) {
18             wordIndex2 = i;
19             if (wordIndex1 != -1) {
20                 minDistance = Math.min(minDistance, Math.abs(wordIndex1 - wordIndex2));
21             }
22         }
23     }
24 
25     return minDistance;
26 }

 

Implementation

Time Complexity: O(N) where N is the array size

Space Complexity: O(1) Constant space

 

References

以上是关于Leetcode solution 243: Shortest Word Distance的主要内容,如果未能解决你的问题,请参考以下文章

sh instalación

sh Adicionar /removerrepositóriosapt

sh Adicionar /removerrepositóriosapt

sh Migración

sh Migración

sh Archivodeconfiguracióndegit