第一题 243 Shortest Word Distance
算法
分别记录下两个index的值,不断向前滚动。求最小值。1234567891011121314151617public class shortestDistance243 { public int shortestDistance(String[] words, String word1, String word2) { int word1_index = Integer.MAX_VALUE, word2_index = Integer.MAX_VALUE, distance = Integer.MAX_VALUE;; for (int i = 0; i < words.length; i++) { String word = words[i]; if (word.equals(word1)) { word1_index = i; distance = Math.min(Math.abs(word1_index - word2_index), distance); } if (word.equals(word2)) { word2_index = i; distance = Math.min(Math.abs(word1_index - word2_index), distance); } } return distance; }}