1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        ?LeetCode刷題實戰(zhàn)243:最短單詞距離

        共 1777字,需瀏覽 4分鐘

         ·

        2021-04-23 10:52

        算法的重要性,我就不多說了吧,想去大廠,就必須要經(jīng)過基礎知識和業(yè)務邏輯面試+算法面試。所以,為了提高大家的算法能力,這個公眾號后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !

        今天和大家聊的問題叫做 最短單詞距離,我們先來看題面:
        https://leetcode-cn.com/problems/shortest-word-distance/

        Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

        給定一個單詞列表和兩個單詞 word1 和 word2,返回列表中這兩個單詞之間的最短距離。

        示例


        示例:
        假設 words = ["practice", "makes", "perfect", "coding", "makes"]
        輸入: word1 = “coding”, word2 = “practice”
        輸出: 3


        輸入: word1 = "makes", word2 = "coding"
        輸出: 1

        注意:
        你可以假設 word1 不等于 word2, 并且 word1 和 word2 都在列表里。


        解題

        思路:遍歷一遍字符串,記錄最后一次出現(xiàn)的位置即可,然后找出差距最小的。


        class Solution {
        public:
            int shortestDistance(vector<string>& words, string word1, string word2) {
              int i1 = -1, i2 = -1, mindis = INT_MAX;
              for(int i = 0; i < words.size(); ++i)
              {
                if(words[i] == word1)
                  i1 = i;
                else if(words[i] == word2)
                  i2 = i;
                if(i1 != -1 && i2 != -1)
                  mindis = min(mindis, abs(i1-i2));
              }
              return mindis;
            }
        };


        好了,今天的文章就到這里,如果覺得有所收獲,請順手點個在看或者轉發(fā)吧,你們的支持是我最大的動力 。

        上期推文:

        LeetCode1-240題匯總,希望對你有點幫助!
        LeetCode刷題實戰(zhàn)241:為運算表達式設計優(yōu)先級
        LeetCode刷題實戰(zhàn)242:有效的字母異位詞

        瀏覽 26
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            少妇一级婬片免费 | 麻豆网站在线免费观看 | 国产一级淫片a视频免费观看 | 国产清纯白嫩初高中在线观看性色 | 宁荣荣张开双腿被强视频 | 调教总裁跪撅含玉势打臀缝bl | 中文字幕第36页 | 91麻豆精品一二三区在线 | 少妇做爰毛片A片成人影院 | 豆花视频黄网在线播放 |