Java&C++题解与拓展——leetcode面试题17.11.单词距离【么的新知识】

71 阅读1分钟
每日一题做题记录,参考官方和三叶的题解

题目要求

思路:模拟

  • 遍历单词数组,两个指针分别指向两个单词,求两个指针下标相减所得最小值即可。

Java

class Solution {
    public int findClosest(String[] words, String word1, String word2) {
        int n = words.length, res = n;
        for(int i = 0, a = -1, b = -1; i < n; i++) {
            String cur = words[i];
            if(cur.equals(word1))
                a = i;
            if(cur.equals(word2))
                b = i;
            if(a != -1 && b != -1)
                res = Math.min(res, Math.abs(a - b));
        }
        return res;
    }
}
  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(1)O(1)

C++

class Solution {
public:
    int findClosest(vector<string>& words, string word1, string word2) {
        int n = words.size(), res = n;
        for(int i = 0, a = -1, b = -1; i < n; i++) {
            string cur = words[i];
            if(cur == word1)
                a = i;
            if(cur == word2)
                b = i;
            if(a != -1 && b != -1)
                res = min(res, abs(a - b));
        }
        return res;
    }
};
  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(1)O(1)

Rust

impl Solution {
    pub fn find_closest(words: Vec<String>, word1: String, word2: String) -> i32 {
        let (mut a, mut b) = (-1, -1);
        let mut res = i32::MAX;
        words.iter().enumerate().for_each(|(i, cur)| {
            if cur == &word1 {
                a = i as i32;
            }
            if cur == &word2 {
                b = i as i32;
            }
            if a != -1 && b != -1 {
                res = res.min((a - b).abs());
            }
        });
        res
    }
}
  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(1)O(1)

总结

是我最喜欢的双指针、快乐光速带走~

学习了一下Rust的容器遍历函数,逐渐学会简单的Rust语法~


欢迎指正与讨论!