zoukankan      html  css  js  c++  java
  • LeetCode 243. Shortest Word Distance

    原题链接在这里:https://leetcode.com/problems/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.

    For example,
    Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

    Given word1 = “coding”word2 = “practice”, return 3.
    Given word1 = "makes"word2 = "coding", return 1.

    Note:
    You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

    题解:

    Time Complexity: O(n). n = words.length.

    Space: O(1).

    AC Java:

     1 class Solution {
     2     public int shortestDistance(String[] words, String word1, String word2) {
     3         if(words == null || words.length == 0 || word1.equals(word2)){
     4             return 0;
     5         }
     6         
     7         int ind1 = -1;
     8         int ind2 = -1;
     9         int res = words.length;
    10         
    11         for(int i = 0; i < words.length; i++){
    12             if(words[i].equals(word1)){
    13                 ind1 = i;
    14                 if(ind2 != -1){
    15                     res = Math.min(res, ind1 - ind2);
    16                 }
    17             }
    18             
    19             if(words[i].equals(word2)){
    20                 ind2 = i;
    21                 if(ind1 != -1){
    22                     res = Math.min(res, ind2 - ind1);
    23                 }
    24             }
    25         }
    26         
    27         return res;
    28     }
    29 }

     跟上Shortest Word Distance IIShortest Word Distance III.

  • 相关阅读:
    代理模式
    面向对象设计原则
    砝码破碎
    阿里EasyExcel使用
    IBM的OpenJ9
    java反射 (复习)
    DecimalFormat保留小数
    Object类
    SQLMAP用法
    SQL盲注之时间注入
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5186287.html
Copyright © 2011-2022 走看看