Problem Solving with Algorithms

반응형

leetcode.com/problems/shortest-word-distance/

n^2으로 풀면 안된다.

class Solution {
    public int shortestDistance(String[] words, String word1, String word2) {
        int i1 = -1, i2 = -1;
        int minDistance = words.length;
        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(word1)) {
                i1 = i;
            } else if (words[i].equals(word2)) {
                i2 = i;
            }

            if (i1 != -1 && i2 != -1) {
                minDistance = Math.min(minDistance, Math.abs(i1 - i2));
            }
        }
        return minDistance;
    }
}
반응형
반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band