zoukankan      html  css  js  c++  java
  • [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;
        }
    }
  • 相关阅读:
    AutoFac
    MEF 基础简介 四
    MEF 基础简介 三
    MEF 基础简介 二
    MEF 基础简介 一
    Ioc原理理解
    .NET里面 abstract class和Interface有什么区别以及用法的展现?
    .NET-ORM框架EF-Code First代码优先
    SQL SERVER PIVOT与用法解释
    SQL Server 中的 NOLOCK 到底是什么意思?
  • 原文地址:https://www.cnblogs.com/xuanlu/p/11879719.html
Copyright © 2011-2022 走看看