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;
        }
    }
  • 相关阅读:
    起泡排序引申出的问题
    关于NPC和NP-Hard问题
    我的书单(更新中)
    OpenCV2学习笔记03:Qt中配置OpenCV环境
    Ubuntu 14.04为浏览器添加Flash插件
    CSS3基础
    HTML5进阶
    拖拽上传及读取文件实现
    生产者消费者模型
    进程
  • 原文地址:https://www.cnblogs.com/xuanlu/p/11879719.html
Copyright © 2011-2022 走看看