<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Han Zhu on Medium]]></title>
        <description><![CDATA[Stories by Han Zhu on Medium]]></description>
        <link>https://medium.com/@zhuhan?source=rss-59a8e3be9735------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*DJIqrCPgGmR5uzs4.</url>
            <title>Stories by Han Zhu on Medium</title>
            <link>https://medium.com/@zhuhan?source=rss-59a8e3be9735------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:17:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zhuhan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[美国总统竞选流程]]></title>
            <link>https://medium.com/@zhuhan/%E7%BE%8E%E5%9B%BD%E6%80%BB%E7%BB%9F%E7%AB%9E%E9%80%89%E6%B5%81%E7%A8%8B-d2e8807d8990?source=rss-59a8e3be9735------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2e8807d8990</guid>
            <category><![CDATA[elections]]></category>
            <dc:creator><![CDATA[Han Zhu]]></dc:creator>
            <pubDate>Fri, 03 Jul 2020 06:36:55 GMT</pubDate>
            <atom:updated>2020-07-09T17:27:32.847Z</atom:updated>
            <content:encoded><![CDATA[<p>美国每四年竞选一次总统，今年（2020）将举行一次竞选。大选时间是11月第一个星期一之后的第一个星期二，也就是11月3号。大选将近，我们来了解一下美国总统究竟是怎么选出来的。</p><h3>竞选总统的条件</h3><p>首先，一个人想要竞选美国总统，必须满足以下三个条件：</p><ol><li>是自然出生的美国公民 （Natural Born Citizen)：<br>什么样的人算自然出生的美国公民呢？以下两种人：<br> * 出生在美国境内的人。<br> * 父母有一方是美国公民的人。<br>也就是说，只要你出生在美国境内，不管你父母是不是美国人，你都是自然出生的美国公民。另一方面，只要你父母有一方是美国公民，不管你出生在哪，你都是自然出生的美国公民。</li><li>年龄至少35岁。</li><li>在美国居住至少14年。</li></ol><p>满足以上三个条件的任何人都可以竞选美国总统。</p><h3>党内竞选</h3><p>在竞选之初，每个党派都有多位候选人想要竞选总统，但只能选出一位作为总统候选人（Presidential Nominee），在之后的大选中和其他党派的候选人PK。</p><p>美国最大的两个政党是共和党和民主党，也有一些其他的小众党派，例如自由党（Libertarian Party），但由于影响太小，竞选总统几乎没有可能，所以总统大选最终都是在共和党和民主党两党之间竞争。今年共和党候选人是川普，民主党是拜登。</p><p>总统候选人选出后，他们还会选出与自己合作的副总统候选人，叫做Running Mate。之后两个小伙伴就可以周游全国参加竞选活动了（Campaign）。</p><h3>大选（General Election）</h3><p>在文章的开头提过，今年大选的时间是11月3日。在那天，美国公民便会纷纷上街投票，在共和党和民主党候选人之间，选出自己支持的一方。</p><p>投票结束后，每个州会各自统计州内的票数，之后算出全国总票数，这些票数叫做Popular Vote。共和党和民主党候选人中，有一方会赢得popular vote。<strong>这里要澄清一点，赢得popular vote并不代表能当上总统。</strong>竞选还有很重要的一环：选举人团。</p><h3>选举人团（Electoral College）</h3><p>美国总统是由公民投票选出来的么？并不直接是。最直接的说，美国总统是由选举人团选出来的。那选举人团究竟是什么呢？</p><p>全国大选后，将由538名选举人（Elector）组成选举人团，在大约一个月后，也就是12月中旬，投票选出总统和副总统。</p><p>选举人团是如何组成的呢？每个州有固定的选举人数目，这个数目大致与每个州在众议院（House of Representatives）里议员的数目成比例，众议员数目又大致与州人口成比例，所以选举人数目大致与州人口成比例，一个州的人口越多，选举人越多。人口最多的加州，有55个选举人。而人烟稀少的州，例如阿拉斯加，只有三个选举人。</p><p>这里要澄清一点，写到这里，我都是写的选举人，而不是选举人票，这是因为，每个选举人票背后，都是活生生的一个人。这些选举人都是谁呢？选举人通常都是共和党或民主党的成员。回想之前提到的，大选之后，每个州都会统计票数，也就是popular vote。这个票数并不决定美国总统是谁，那这个票数有什么用呢？<strong>赢得州内popular vote的政党，可以指定这个州选举人的所有人选。</strong>这也叫做Winner-take-all制度。</p><p>举个例子，民主党往往都会赢得加州的大选，也就意味着，民主党可以选出55个“自己人”，加入538人的选举人团，去参加12月的选举人投票。这里可以暂时认为，两党选出的选举人，永远都会投给自己党派的候选人（有例外）。</p><p>选举人团组成后，每人有一票，总共538票，赢得票池中的半数以上（Majority），也就是至少270票，就可以当选总统了。</p><h3>特殊情况</h3><p><strong>赢得Popular Vote，却输掉选举人票</strong></p><p>一个总统候选人，有没有可能赢得全国popular vote，也就是说，全美参选公民的票数得票第一，但却输掉选举人票，没有当成总统呢？答案是可以的。</p><p>举个简单的例子，假设美国只有两个州，人少州和人多州。人少州有一千人口，人多州有两千人口。选举人票和人口成正比，所以人少州给到一票选举人票，人多州给两票。另外，有两个总统候选人A和B。</p><p>大选结束，人少州的人都是A的狂热粉丝，一千人都投给了A，于是人少州popular vote的结果是A：B = 1000：0，选举人票结果为1：0。人多州呢，有六百人投给了A，1400人投给了B，于是人多州popular vote的结果是600：1400，选举人票结果是0：2。两个州的票数加到一起，最终全国popular vote的结果是1600：1400，但选举人票的结果是1：2。A赢得了popular vote，却输掉了总统席位。</p><p>这种情况在2016年就发生了，希拉里赢得了popular vote（65,853,514：62,984,828），却输掉了选举人票（227：304）。</p><p>美国各州按大选投票情况可以分为红州，蓝州，和摇摆州。Winner-take-all制度带来的影响，便是摇摆州投票结果对最终大选结果的影响，比红州和蓝州大得多。像加州或华盛顿州这样铁打的蓝营，投票结果都是60几个百分点，对30几个百分点，对比悬殊，民主党没有不赢的可能。而摇摆州双方实力相当，天平稍稍向一方倾斜，这个周的选举人票便易主，尤其是人口众多的摇摆州，比如德州，有38张选举人票，佛罗里达州，29张选举人票，对大选结果是决定性的。</p><p>Winner-take-all制度带来的另外一个影响，就是一个州的弱势党派，没有任何在这个州竞选的动力。共和党候选人，有必要在华盛顿州跑活动么？没有。选举人票又不按popular vote的比例分配，即便共和党大力出奇迹，把票数拉到了55%比45%，也没有任何意义。与其在对方的铁营浪费经费，还不如把钱都花在摇摆州里。</p><p>写到这里，就有几个有趣的问题了。每个美国公民人手一票，既然摇摆州的投票结果对大选结果的影响比其他州大很多，那么每人手里这张票，是一样分量么？既然红州和蓝州的投票结果基本已经决定了，选举人票赢家通吃，那作为红州或蓝州的公民，投出的一票，有多少意义呢？</p><p><strong>失信选举人（Faithless Elector）</strong></p><p>细心的同学可能发现了，希拉里和川普在2016年选举人票的结果是227对304，总共531张票，可是选举人团总共有538人，剩下的七张票去哪了呢？这里要提到选举人投票的规则，以及失信选举人的概念。</p><p>前文提到，选举人一般都会投给自己党派的候选人，但是有例外。实际上，美国宪法规定，选举人有权利投给任何人作总统和副总统，是的任何人，投给他爹都没人拦着。这就很有意思了，作为民主党和共和党，怎么能保证自己的选举人投给自己呢？</p><p>选举人当选后有一个pledge的过程，大概可以理解为，会宣誓对己方效忠。这个过程是没有任何法律效力的，选举人仍然可以自由的把票投给任何人。如果一个选举人没有把票投给自己党派的候选人，不论是总统还是副总统，这个选举人就被称为失信选举人。这种情况极少发生，毕竟做出这样的举动，是要付出极大的政治资本的，而且对投票结果影响很小。</p><p>一个失信选举人对投票结果的影响微乎其微，但一群呢？</p><p>2016年大选过后，从popular vote的结果来看，假设每个选举人票都顺利投给己方党派，那么美国总统也可以确定是川普了。从大选结果公布到选举人投票有一个多月的时间，川普是个很有争议的总统不用多说了，有些选举人在看到这样的票型之后，开始酝酿一个大动作。</p><p>科罗拉多州的选举人Michael Baca和华盛顿州的选举人Bret Chiafalo，计划拉拢选举人团不要投给川普。他们计划的最优结果是联合至少270人，将票投给一位较为温和的共和党人，这样同时可以说服共和党选举人以及民主党选举人，让川普败选。这个想法较为理想，稍微现实一点的是，说服至少37名共和党候选人投票给随便另一人，将川普的票数拉到最多269票。这种情况下，没有任何一人得到majority，将由众议院投票选出总统。</p><p>这个行动最后以失败告终。投票时，共有十人失信，计划将票投给非自己党派候选人的另外一人，其中一位选举人被迫被其他人替换，另外两人被迫重新投票并投给己方候选人，剩下七人成功投给自己想投的人，所以538票除去七票，剩余531票归川普和希拉里所有。虽然以失败告终，但如此多的失信选举人在历史上都是十分罕见的，在当年也是轰动一时。有兴趣的同学可以搜索“Hamilton Electors”了解更多。</p><h3>小结</h3><p>围绕着美国大选说了很多，重点放在选举人制度。大选将近，川普会连任么？还会出现像2016年那么大的drama么？我们拭目以待。</p><p>本文信息事实均从美国政府官方网站以及权威媒体引用。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2e8807d8990" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[LeetCode] 6. ZigZag Conversion]]></title>
            <link>https://medium.com/@zhuhan/leetcode-6-zigzag-conversion-fc42ab9750fa?source=rss-59a8e3be9735------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc42ab9750fa</guid>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Han Zhu]]></dc:creator>
            <pubDate>Fri, 27 Dec 2019 06:03:33 GMT</pubDate>
            <atom:updated>2019-12-27T06:03:33.973Z</atom:updated>
            <content:encoded><![CDATA[<p>The string &quot;PAYPALISHIRING&quot; is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)</p><pre>P   A   H   N<br>A P L S I I G<br>Y   I   R</pre><p>And then read line by line: &quot;PAHNAPLSIIGYIR&quot;</p><p>Write the code that will take a string and make this conversion given a number of rows:</p><pre>string convert(string s, int numRows);</pre><p><strong>Example 1:</strong></p><pre><strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 3<br><strong>Output:</strong> &quot;PAHNAPLSIIGYIR&quot;</pre><p><strong>Example 2:</strong></p><pre><strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 4<br><strong>Output:</strong> &quot;PINALSIGYAHRPI&quot;<br><strong>Explanation:</strong></pre><pre>P     I    N<br>A   L S  I G<br>Y A   H R<br>P     I</pre><p><strong>Thought Process:</strong></p><p>This is a straightforward question. Create one string for each row. Iterate the input string and append its characters to the corresponding row. We can use one flag to track whether we are going down the rows or up.</p><p><strong>Solution:</strong></p><pre>class Solution:<br>    def convert(self, s: str, numRows: int) -&gt; str:<br>        if len(s) == 0 or len(s) == 1 or numRows == 1:<br>            return s<br>        <br>        rows = [&quot;&quot;] * numRows            <br>        i = 0<br>        goingDown = False<br>        <br>        for char in s:<br>            rows[i] = &quot;&quot;.join([rows[i], char])<br>            if i == 0 or i == numRows - 1:<br>                goingDown = not goingDown<br>            i += 1 if goingDown else -1<br>        <br>        return &quot;&quot;.join(rows)</pre><p><strong>Complexity Analysis:</strong></p><p>Time complexity: O(n).</p><p>Space complexity: the “rows” list will contain maximum n characters. So space complexity is also O(n).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc42ab9750fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[LeetCode] 5. Longest Palindromic Substring]]></title>
            <link>https://medium.com/@zhuhan/leetcode-5-longest-palindromic-substring-ec13fedd1dac?source=rss-59a8e3be9735------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec13fedd1dac</guid>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Han Zhu]]></dc:creator>
            <pubDate>Wed, 18 Dec 2019 05:40:25 GMT</pubDate>
            <atom:updated>2019-12-18T05:40:25.384Z</atom:updated>
            <content:encoded><![CDATA[<p>Given a string <strong>s</strong>, find the longest palindromic substring in <strong>s</strong>. You may assume that the maximum length of <strong>s</strong> is 1000.</p><p><strong>Example 1:</strong></p><pre><strong>Input:</strong> &quot;babad&quot;<br><strong>Output:</strong> &quot;bab&quot;<br><strong>Note:</strong> &quot;aba&quot; is also a valid answer.</pre><p><strong>Example 2:</strong></p><pre><strong>Input:</strong> &quot;cbbd&quot;<br><strong>Output:</strong> &quot;bb&quot;</pre><p><strong>Thought process:</strong></p><p>A naive solution is to iterate through all substrings of the given string [O(n²)] and check if it is a palindrome for each substring [O(n)], which results in a time complexity of O(n³). This is not efficient.</p><p>The naive solution does lots of redundant work, by repetitively checking if a same substring is palindrome. For example, if the input string is “abbac”, and we checked that substring “bb” is a palindrome. Later we check if the substring “abba” is a palindrome. During this process, we iterate through “bb” again.</p><p>The solution can be optimized using dynamic programming. There are four elements of dynamic programming:</p><ol><li>Sub-structure: create a matrix of length n, where n is the length of input string s. dp[i][j] is a boolean representing whether s[i][j] is a palindrome.</li><li>Initialization: dp[i][i] is automatically true because one character is always a palindrome.</li><li>Transition: there are two cases. If i + 1 == j, i.e. s[i] and s[j] are neighboring characters, then dp[i][j] = True if s[i] == s[j]. Otherwise, if s[i] == s[j], we look and the enclosed substring of s[i:j], s[i+1:j-1]. If that is a palindrome then s[i][j] is also a palindrome. dp[i][j] = True.</li><li>Answer: we will use a string to keep track of the longest palindrome seen so far.</li></ol><p>The crux of this problem is actually not the DP elements, rather, how to iterate through the matrix. Iterating through the matrix row by row, like we are used to, does not work, because to determine if s[0:3] is a palindrome, we need to know beforehand whether s[1:2] is a palindrome. Therefore, we need to iterate through the matrix diagonally.</p><p><strong>Solution:</strong></p><pre>class Solution:<br>    def longestPalindrome(self, s: str) -&gt; str:<br>        if not s or len(s) == 1:<br>            return s<br>        <br>        dp = [[False] * len(s) for i in range(len(s))]<br>        for i in range(len(s)):<br>            dp[i][i] = True<br>            <br>        longest = s[0]<br>        for i in range(len(s)):<br>            for j in range(i + 1, len(s)):<br>                row = j - i - 1<br>                col = j<br>                <br>                if s[row] == s[col]:<br>                    if row + 1 == col:<br>                        dp[row][col] = True<br>                    else:<br>                        dp[row][col] = dp[row + 1][col - 1]<br>                    if dp[row][col] and col - row + 1 &gt; len(longest):<br>                        longest = s[row:col + 1]<br>        return longest<br>    <br>    def printMatrix(self, m):<br>        for l in m:<br>            print(l)</pre><p><strong>Complexity Analysis:</strong></p><ul><li>Time: O(n²)</li><li>Space: O(n²)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec13fedd1dac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[LeetCode] 3. Longest Substring Without Repeating Characters]]></title>
            <link>https://medium.com/@zhuhan/leetcode-3-longest-substring-without-repeating-characters-458fd9105404?source=rss-59a8e3be9735------2</link>
            <guid isPermaLink="false">https://medium.com/p/458fd9105404</guid>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Han Zhu]]></dc:creator>
            <pubDate>Thu, 05 Dec 2019 06:31:09 GMT</pubDate>
            <atom:updated>2019-12-05T06:31:09.285Z</atom:updated>
            <content:encoded><![CDATA[<p>Given a string, find the length of the <strong>longest substring</strong> without repeating characters.</p><p><strong>Example 1:</strong></p><pre><strong>Input: </strong>&quot;abcabcbb&quot;<br><strong>Output: </strong>3 <br><strong>Explanation:</strong> The answer is &quot;abc&quot;, with the length of 3.</pre><p><strong>Example 2:</strong></p><pre><strong>Input: </strong>&quot;bbbbb&quot;<br><strong>Output: </strong>1<br><strong>Explanation: </strong>The answer is &quot;b&quot;, with the length of 1.</pre><p><strong>Example 3:</strong></p><pre><strong>Input: </strong>&quot;pwwkew&quot;<br><strong>Output: </strong>3<br><strong>Explanation: </strong>The answer is &quot;wke&quot;, with the length of 3. <br>             Note that the answer must be a <strong>substring</strong>, &quot;pwke&quot; is a <em>subsequence</em> and not a substring.</pre><p><strong>Thought Process:</strong></p><p>A brute force solution is to examine all substrings [O(n²)], check if a substring has repeating characters for every substring [O(n)], and keep track of the longest. This results in a time complexity of O(n³), which is not efficient.</p><p>The brute force solution could avoid checking repeating characters for some substrings. For the example “abcabcbbb”, when we checked “abca” has repeating characters, there is no point checking “abcab” for repeating characters.</p><p>To optimize the brute force solution, we can use a sliding window and a dictionary. A sliding window means we have two pointers, left and right, to represent the left and right ends of a substring. We will move them along the string as we examine the substrings. The dictionary keeps track of the mappings of a character and its rightmost index in the string. As we increment the right end of the substring, we check if s[right] is in the dictionary. If so, we skip left to the last seen index of s[right], so that there is no repeating s[right] in the new substring. Otherwise, we put s[right] =&gt; right mapping into the dictionary.</p><p><strong>Solution:</strong></p><pre>class Solution:<br>    def lengthOfLongestSubstring(self, s: str) -&gt; int:<br>        left = 0<br>        right = 0<br>        index = {}<br>        longest_length = 0<br>        <br>        while right &lt; len(s):<br>            if s[right] in index:<br>                # The rightmost s[right] could be less than left<br>                left = max(index[s[right]] + 1, left)<br>            longest_length = max(longest_length, right - left + 1)<br>            index[s[right]] = right<br>            right += 1<br>        return longest_length</pre><p><strong>Complexity Analysis:</strong></p><p>Time complexity: O(n)</p><p>Space complexity: O(n)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=458fd9105404" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[LeetCode] 2. Add Two Numbers]]></title>
            <link>https://medium.com/@zhuhan/leetcode-2-add-two-numbers-bcf536ec8ee1?source=rss-59a8e3be9735------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcf536ec8ee1</guid>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Han Zhu]]></dc:creator>
            <pubDate>Wed, 04 Dec 2019 05:18:32 GMT</pubDate>
            <atom:updated>2019-12-04T05:18:32.421Z</atom:updated>
            <content:encoded><![CDATA[<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The digits are stored in <strong>reverse order</strong> and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.</p><p>You may assume the two numbers do not contain any leading zero, except the number 0 itself.</p><p><strong>Example:</strong></p><pre><strong>Input:</strong> (2 -&gt; 4 -&gt; 3) + (5 -&gt; 6 -&gt; 4)<br><strong>Output:</strong> 7 -&gt; 0 -&gt; 8<br><strong>Explanation:</strong> 342 + 465 = 807.</pre><p><strong>Thought process:</strong></p><p>Because the numbers are represented as a linked list in the reverse order, we can simply iterate through both lists together and add the corresponding nodes. Note there is an edge case where both lists are iterated through but there is a remaining carry of one, e.g. 5 + 5 = 10. We need to not only check for list node is true but also carry is true.</p><p><strong>Solution:</strong></p><pre># Definition for singly-linked list.<br># class ListNode:<br>#     def __init__(self, x):<br>#         self.val = x<br>#         self.next = None</pre><pre>class Solution:<br>    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -&gt; ListNode:<br>        head = ListNode(-1)<br>        previous = head<br>        carry = 0<br>        <br>        while l1 or l2 or carry:<br>            add = 0<br>            if l1:<br>                add += l1.val<br>                l1 = l1.next<br>            if l2:<br>                add += l2.val<br>                l2 = l2.next<br>            add += carry<br>            <br>            digit = add % 10<br>            carry = add // 10<br>            <br>            current = ListNode(digit)<br>            previous.next = current<br>            previous = current<br>        return head.next</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcf536ec8ee1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[LeetCode] 1. Two Sum]]></title>
            <link>https://medium.com/@zhuhan/leetcode-1-two-sum-20de4c9886d6?source=rss-59a8e3be9735------2</link>
            <guid isPermaLink="false">https://medium.com/p/20de4c9886d6</guid>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Han Zhu]]></dc:creator>
            <pubDate>Tue, 03 Dec 2019 09:09:30 GMT</pubDate>
            <atom:updated>2019-12-03T09:09:30.515Z</atom:updated>
            <content:encoded><![CDATA[<p>Given an array of integers, return <strong>indices</strong> of the two numbers such that they add up to a specific target.</p><p>You may assume that each input would have <strong><em>exactly</em></strong> one solution, and you may not use the <em>same</em> element twice.</p><p><strong>Example:</strong></p><pre>Given nums = [2, 7, 11, 15], target = 9,</pre><pre>Because nums[<strong>0</strong>] + nums[<strong>1</strong>] = 2 + 7 = 9,<br>return [<strong>0</strong>, <strong>1</strong>].</pre><p><strong>Thought Process</strong></p><p>An O(n²) solution is trivial. Using a dictionary, we can achieve a more efficient O(n) solution. Since we cannot use the same element twice, we know that one element must pair with another in the solution. We can iterate through the list, use a dictionary to keep track of element seen and its index, and look up the dictionary to check if there exists a number that can sum to target with the current number.</p><p><strong>Solution</strong></p><pre>class Solution:<br>    def twoSum(self, nums: List[int], target: int) -&gt; List[int]:<br>        difference = {}<br>        indices = []<br>        <br>        for i, num in enumerate(nums):<br>            if num in difference:<br>                indices.append(difference[num])<br>                indices.append(i)<br>                break<br>            difference[target - num] = i<br>        return indices</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20de4c9886d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>