zoukankan      html  css  js  c++  java
  • 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
    
    

     

     
  • 相关阅读:
    运算符
    数据类型
    试题汇总
    文件读写
    Python操作
    字符串常用函数 void
    向量叉乘求任意多边形面积,凹凸均可 void
    约瑟夫问题各种求解办法 void
    大数类相关计算(c语言版) void
    求解一元多次方程(迭代法) void
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13855373.html
Copyright © 2011-2022 走看看