Golang 13ms Two indexes


  • 0
    R
    import "math"
    
    func shortestDistance(words []string, word1 string, word2 string) int {
        p1 := -1
        p2 := -1
        min := math.MaxInt32
        for i:=0; i < len(words); i++ {
            if words[i] == word1 {
                p1 = i
            } else if words[i] == word2 {
                p2 = i
            }
            
            if p1 != -1 && p2 != -1 {
                n := p1 - p2
                if n < 0 {
                    n = -n
                }
                if min > n {
                    min = n
                }
            }
        }
        return min
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.