Skip to content

Commit

Permalink
[Array] Optimize and add a solution to Shortest Word Distance i and iii
Browse files Browse the repository at this point in the history
  • Loading branch information
Yi Gu committed Nov 28, 2016
1 parent b75e3aa commit b722354
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,18 @@
class ShortestWordDistance {
func shortestDistance(_ words: [String], _ word1: String, _ word2: String) -> Int {
var distance = Int.max
var firstIndex: Int?
var secondIndex: Int?
var firstIndex = -1, secondIndex = -1

for (i, word) in words.enumerated() {
if word == word1 {
if let sec = secondIndex {
distance = min(distance, i - sec)
}
firstIndex = i
} else if word == word2 {
if let fir = firstIndex {
distance = min(distance, i - fir)
}
}
if word == word2 {
secondIndex = i
}
if firstIndex != -1 && secondIndex != -1 {
distance = min(distance, abs(firstIndex - secondIndex))
}
}

return distance
Expand Down
34 changes: 34 additions & 0 deletions Array/ShortestWordDistanceIII.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* Question Link: https://leetcode.com/problems/shortest-word-distance-iii/
* Primary idea: Iterate and update index and distance when encounter word1 or word2, use
* a temp variable to memorize the previous postion if word1 == word2
*
* Time Complexity: O(n), Space Complexity: O(1)
*/

class ShortestWordDistanceIII {
func shortestWordDistance(_ words: [String], _ word1: String, _ word2: String) -> Int {
var idx1 = -1, idx2 = -1, res = Int.max

for (i, word) in words.enumerated() {
var prev = idx1

if word == word1 {
idx1 = i
}
if word == word2 {
idx2 = i
}

if idx1 != -1 && idx2 != -1 {
if word1 == word2 && prev != -1 && prev != idx1 {
res = min(res, idx1 - prev)
} else if idx1 != idx2 {
res = min(res, abs(idx1 - idx2))
}
}
}

return res
}
}

0 comments on commit b722354

Please sign in to comment.