243. Shortest Word Distance 最短的单词index之差

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

思路:i同时给了p1 p2,所以两者不会相差太远。
这个思路好难以想到啊,似乎也就这道题能用
感觉这个优化很生硬。那就随便写写吧
时间n,空间1


暴力:存两个arraylist,时间n^2, 空间n


 

class Solution {
    public int shortestDistance(String[] words, String word1, String word2) {
        //cc
        if (words == null || words.length == 0)
            return 0;
        int p1 = -1, p2 = -1, min = Integer.MAX_VALUE;
        
        //for循环,内部每次都更新
        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(word1)) {
                p1 = i;
            }
            
            if (words[i].equals(word2)) {
                p2 = i;
            }
            
            if ((p1 != -1) && (p2 != -1)) {
                min = Integer.min(min, Math.abs(p2 - p1));
            }
        }
        
        //返回
        return min;
    }
}
View Code

 

 
原文地址:https://www.cnblogs.com/immiao0319/p/13855373.html