forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Array] Optimize and add a solution to Shortest Word Distance i and iii
- Loading branch information
Yi Gu
committed
Nov 28, 2016
1 parent
b75e3aa
commit b722354
Showing
2 changed files
with
40 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |