• [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;
        }
    }
  • 相关阅读:
    SqlHelper
    C#中gridView常用属性和技巧介绍
    oracle中的存储过程例子
    log4j.properties配置详解
    Ant之build.xml
    jQuery源码
    jQuery实现分页
    mysql中log
    SQL只获取字段中的中文字符
    子Repeater获取父级Repeater绑定项的值
  • 原文地址:https://www.cnblogs.com/xuanlu/p/11879719.html
Copyright © 2020-2023  润新知