{"id":924,"date":"2017-04-30T11:53:56","date_gmt":"2017-04-30T03:53:56","guid":{"rendered":"http:\/\/www.mrtblog.cn\/?p=924"},"modified":"2023-03-05T16:44:39","modified_gmt":"2023-03-05T08:44:39","slug":"%e3%80%90c%e3%80%91%e3%80%90leetcode%e3%80%912020-4-222020-4-29","status":"publish","type":"post","link":"http:\/\/www.mrtblog.cn\/?p=924","title":{"rendered":"\u3010C++\u3011\u3010LeetCode\u30112020.4.22~2020.4.29"},"content":{"rendered":"<div class='epvc-post-count'><span class='epvc-eye'><\/span>  <span class=\"epvc-count\"> 1,517<\/span><span class='epvc-label'> Views<\/span><\/div><p><em><strong>1. Two Sum<\/strong><\/em><\/p>\n<p>Given an array of integers, return&nbsp;<strong>indices<\/strong>&nbsp;of the two numbers such that they add up to a specific target.<\/p>\n<p>You may assume that each input would have&nbsp;<strong><em>exactly<\/em><\/strong>&nbsp;one solution, and you may not use the&nbsp;<em>same<\/em>&nbsp;element twice.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre>Given nums = [2, 7, 11, 15], target = 9,\n\nBecause nums[0] + nums[1] = 2 + 7 = 9,\nreturn [0, 1].\n<\/pre>\n<pre class=\"highlight\"><code class=\"language-cpp line-numbers\">\nclass Solution {\npublic:\n    vector&lt;int&gt; twoSum(vector&lt;int&gt;&amp; nums, int target) {\n\n        map&lt;int,int&gt; numsMap;\n\n        for (int i = 0; i &lt; int(nums.size()); ++i) {\n            map&lt;int, int&gt;::iterator iter = numsMap.find(target - nums[i]);\n            if (iter != numsMap.end()) {\n                return {iter-&gt;second, i};\n            } else {\n                numsMap.insert(make_pair(nums[i], i));\n            }\n        }\n        return {-1, -1};\n    }\n};\n<\/code><\/pre>\n<hr>\n<p><em><strong>2.&nbsp;Add Two Numbers<\/strong><\/em><\/p>\n<p>You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.<\/p>\n<p>You may assume the two numbers do not contain any leading zero, except the number 0 itself.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre>Input: (2 -&gt; 4 -&gt; 3) + (5 -&gt; 6 -&gt; 4)\nOutput: 7 -&gt; 0 -&gt; 8\nExplanation: 342 + 465 = 807.\n<\/pre>\n<pre class=\"highlight\"><code class=\"language-cpp line-numbers\">\n\/**\n* Definition for singly-linked list.\n* struct ListNode {\n*     int val;\n*     ListNode *next;\n*     ListNode(int x) : val(x), next(NULL) {}\n* };\n*\/\nclass Solution {\npublic:\n    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {\n\n        int addVal = 0;\n        ListNode *HeadNode = new ListNode(0);\n        ListNode *WalkNode = HeadNode;\n        while (l1 &amp;&amp; l2) {\n            int tmpVal = l1-&gt;val + l2-&gt;val + addVal;\n\n            WalkNode-&gt;next = new ListNode(tmpVal % 10);\n            WalkNode = WalkNode-&gt;next;\n\n            addVal = tmpVal \/ 10;\n            l1 = l1-&gt;next;\n            l2 = l2-&gt;next;\n        }\n\n        while (l1) {\n            int tmpVal = l1-&gt;val + addVal;\n\n            WalkNode-&gt;next = new ListNode(tmpVal % 10);\n            WalkNode = WalkNode-&gt;next;\n\n            addVal = tmpVal \/ 10;\n            l1 = l1-&gt;next;\n        }\n\n        while (l2) {\n            int tmpVal = l2-&gt;val + addVal;\n\n            WalkNode-&gt;next = new ListNode(tmpVal % 10);\n            WalkNode = WalkNode-&gt;next;\n\n            addVal = tmpVal \/ 10;\n            l2 = l2-&gt;next;\n        }\n\n        if (addVal) {\n            WalkNode-&gt;next = new ListNode(addVal);\n            addVal = 0;\n        }\n\n        if (HeadNode) {\n            return HeadNode-&gt;next;\n        }\n\n        return NULL;\n    }\n};\n<\/code><\/pre>\n<hr>\n<p><strong><em>3. Longest Substring Without Repeating Characters<\/em><\/strong><br \/>\nGiven a string, find the length of the longest substring without repeating characters.<\/p>\n<p><strong>Example 1:<\/strong><br \/>\nInput: &#8220;abcabcbb&#8221;<br \/>\nOutput: 3<br \/>\nExplanation: The answer is &#8220;abc&#8221;, with the length of 3.<\/p>\n<p><strong>Example 2:<\/strong><br \/>\nInput: &#8220;bbbbb&#8221;<br \/>\nOutput: 1<br \/>\nExplanation: The answer is &#8220;b&#8221;, with the length of 1.<\/p>\n<p><strong>Example 3:<\/strong><br \/>\nInput: &#8220;pwwkew&#8221;<br \/>\nOutput: 3<br \/>\nExplanation: The answer is &#8220;wke&#8221;, with the length of 3.<br \/>\nNote that the answer must be a substring, &#8220;pwke&#8221; is a subsequence and not a substring.<\/p>\n<pre class=\"highlight\"><code class=\"language-cpp line-numbers\">\nclass Solution {\npublic:\n    int lengthOfLongestSubstring(string s) {\n        if (s.size() &lt;= 1) {\n            return s.size();\n        }\n        int nowCount = 0;\n        int maxCount = 0;\n        int tmpDistance = 0;\n        map&lt;char, int&gt; char2Index;\n        for (size_t i = 0; i &lt; s.size(); ++i) {\n            map&lt;char, int&gt;::iterator iter = char2Index.find(s[i]);\n            if (iter == char2Index.end()) {\n                \/\/not found \u7d2f\u8ba1\/\u8bb0\u5f55\n                nowCount++;\n                char2Index.insert(make_pair(s[i], i));\n            } else {\n                \/\/find \u5237\u65b0nowCount\n                tmpDistance = i - iter-&gt;second;\/\/\u91cd\u590d\u4e32\u8ddd\u79bb\n                \/\/nowCount\u5c0f,\u8bf4\u660e\u5728\u91cd\u590d\u70b9\u53f3\u8fb9,\u7ee7\u7eed\u52a0;nowCount\u5927,\u8bf4\u660e\u5728\u91cd\u590d\u70b9\u5de6\u8fb9,\u4e0d\u52a0\u4e86\n                nowCount = nowCount &lt; tmpDistance ? nowCount + 1 : tmpDistance;\n                iter-&gt;second = i;\/\/\u66f4\u65b0\u4f4d\u7f6e\n            }\n\n            maxCount = maxCount &lt; nowCount ? nowCount : maxCount;\n        }\n        return maxCount;\n    }\n};\n<\/code><\/pre>\n<hr>\n<p><em><strong>4. Median of Two Sorted Arrays<\/strong><\/em><\/p>\n<p>There are two sorted arrays nums1 and nums2 of size m and n respectively.<\/p>\n<p>Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).<\/p>\n<p>You may assume nums1 and nums2 cannot be both empty.<\/p>\n<p><strong>Example 1:<\/strong><br \/>\nnums1 = [1, 3]<br \/>\nnums2 = [2]<\/p>\n<p>The median is 2.0<\/p>\n<p><strong>Example 2:<\/strong><br \/>\nnums1 = [1, 2]<br \/>\nnums2 = [3, 4]<\/p>\n<p>The median is (2 + 3)\/2 = 2.5<\/p>\n<pre class=\"highlight\"><code class=\"language-cpp line-numbers\">\nclass Solution {\npublic:\n    double findMedianSortedArrays(vector&lt;int&gt;&amp; nums1, vector&lt;int&gt;&amp; nums2) {\n        size_t Len1 = nums1.size();\n        size_t Len2 = nums2.size();\n        int mid1 = 0, mid2 = 0;\n\n        int i = 0, j = 0;\n        int Count = 0;\n        int MaxVal = 9999999;\n        while ((i &lt; Len1 || j &lt; Len2)) {\n            \/\/\u627e\u5230\u4e24\u4e2a\u4e2d\u4f4d\u6570\u5373\u53ef\n            int tmp1 = i &lt; Len1 ? nums1[i] : MaxVal;\n            int tmp2 = j &lt; Len2 ? nums2[j] : MaxVal;\n            int tmp = tmp1 &lt; tmp2 ? tmp1 : tmp2;\n\n            if (tmp1 &lt; tmp2) i++;\n            else j++;\n\n            if (Count == (Len1 + Len2 - 1) \/ 2) mid1 = tmp;\n            if (Count == (Len1 + Len2) \/ 2) {\n                mid2 = tmp;\n                break;\n            }\n\n            Count++;\n        }\n        return (mid1 + mid2) \/ 2.0;\n    }\n};\n<\/code><\/pre>\n<hr>\n<p><strong><em>5. Longest Palindromic Substring<\/em><\/strong><br \/>\nGiven a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.<\/p>\n<p><strong>Example 1:<\/strong><br \/>\nInput: &#8220;babad&#8221;<br \/>\nOutput: &#8220;bab&#8221;<br \/>\nNote: &#8220;aba&#8221; is also a valid answer.<\/p>\n<p><strong>Example 2:<\/strong><br \/>\nInput: &#8220;cbbd&#8221;<br \/>\nOutput: &#8220;bb&#8221;<\/p>\n<pre class=\"highlight\"><code class=\"language-cpp line-numbers\">\nclass Solution {\npublic:\n    int findStartEnd(string &amp;s, int len, int &amp;l, int r) {\n        int lastestL = l;\/\/\u6700\u540e\u5339\u914d\u4f4d\u7f6eL\n        int lastestR = r;\/\/\u6700\u540e\u5339\u914d\u4f4d\u7f6eR\n        while (l &gt;= 0 &amp;&amp; l &lt; s.size() &amp;&amp; r &lt; s.size()) {\n            if (s[l] == s[r]) {\n                lastestL = l;\n                lastestR = r;\n                l--;\n                r++;\n                len += 2;\n            } else {\n                break;\n            }\n        }\n\n        l = lastestL;\n        r = lastestR;\n\n        return len;\n    }\n\n    string longestPalindrome(string s) {\n        if (s.size() &lt;= 1) {\n            return s;\n        }\n        int sta = 0, maxLen = 1;\n        for (int i = 0 ; i &lt; s.size(); ++i) {\n            \/\/\u5355\u6570\u5411\u4e24\u8fb9\u6269\u6563,\u5df2\u7ecf\u4e0d\u6ee1\u8db3\u5f53\u524d\u6700\u5927\u503c,\u526a\u679d\n            if ((s.size() - 1 - i) * 2 + 1 &lt;= maxLen) {\n                break;\n            }\n            int l = i - 1;\n            int tmpLen = 0;\n            \/\/ \u5bfb\u627eaba\u7c7b\u578b\n            tmpLen = findStartEnd(s, 1, l, l + 2);\n            if (tmpLen &gt; maxLen) {\n                maxLen = tmpLen;\n                sta = l;\n            }\n\n            l = i;\n            \/\/\u5bfb\u627eabba\u7c7b\u578b\n            tmpLen = findStartEnd(s, 0, l, l + 1);\n            if (tmpLen &gt; maxLen) {\n                maxLen = tmpLen;\n                sta = l;\n            }\n\n        }\n        return s.substr(sta, maxLen);\n    }\n};\n<\/code><\/pre>\n<hr>\n<p><strong><em>6. ZigZag Conversion<\/em><\/strong><br \/>\nThe string &#8220;PAYPALISHIRING&#8221; 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>\n<p>P   A   H   N<br \/>\nA P L S I I G<br \/>\nY   I   R<br \/>\nAnd then read line by line: &#8220;PAHNAPLSIIGYIR&#8221;<\/p>\n<p>Write the code that will take a string and make this conversion given a number of rows:<\/p>\n<p>string convert(string s, int numRows);<\/p>\n<p><strong>Example 1:<\/strong><br \/>\nInput: s = &#8220;PAYPALISHIRING&#8221;, numRows = 3<br \/>\nOutput: &#8220;PAHNAPLSIIGYIR&#8221;<\/p>\n<p><strong>Example 2:<\/strong><br \/>\nInput: s = &#8220;PAYPALISHIRING&#8221;, numRows = 4<br \/>\nOutput: &#8220;PINALSIGYAHRPI&#8221;<br \/>\nExplanation:<br \/>\nP     I    N<br \/>\nA   L S  I G<br \/>\nY A   H R<br \/>\nP     I<\/p>\n<pre class=\"highlight\"><code class=\"language-cpp line-numbers\">\nclass Solution {\npublic:\n\/*\nn = 6\n\n0A         1         1\n1B       1 1       1\n2C     1   1     1\n3D   1     1   1\n4E 1       1 1\n5F         G\n\n0: 2 * (n - 1)\n1: 2 * (n - 2) || 2 * (n - 5)\n2: 2 * (n - 3) || 2 * (n - 4)\n3: 2 * (n - 4) || 2 * (n - 3)\n4: 2 * (n - 5) || 2 * (n - 2)\n5: 2 * (n - 1)\n\n2 * (n - (index + 1)) || 2 * ( n - (n + 1 - (index + 1)))\n2 * ( n - (index + 1)) || 2 * ((index + 1) - 1)\n(n - (index + 1 )) * -1 + n - 1 =  (index + 1) - 1\n((index + 1) - 1) * -1 + n - 1 = n - (index + 1 )\n*\/\n    string convert(string s, int numRows) {\n        if (numRows &lt;= 1 || s.size() &lt;= 1) {\n            return s;\n        }\n        string res = &quot;&quot;;\n        for (size_t i = 0 ; i &lt; numRows; ++i) {\n            size_t j = i;\n            if (j == 0 || j == numRows - 1) {\n                while (j &lt; s.size()) {\n                    res += s[j];\n                    j += 2 * (numRows - 1);\n                }\n            } else {\n                \/\/int sign = -1;\n                int equal = (numRows - (i + 1));\n                while (j &lt; s.size()) {\n                    res += s[j];\n                    j += 2 * equal;\n                    equal = (equal * -1) + numRows - 1;\n                    \/\/sign *= -1;\n                }\n            }\n        }\n\n        return res;\n    }\n};\n<\/code><\/pre>\n<hr>\n<p><strong><em>7. Reverse Integer<\/em><\/strong><\/p>\n<p>Given a 32-bit signed integer, reverse digits of an integer.<\/p>\n<p><strong>Example 1:<\/strong><br \/>\nInput: 123<br \/>\nOutput: 321<\/p>\n<p><strong>Example 2:<\/strong><br \/>\nInput: -123<br \/>\nOutput: -321<\/p>\n<p><strong>Example 3:<\/strong><br \/>\nInput: 120<br \/>\nOutput: 21<br \/>\nNote:<br \/>\nAssume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [\u2212231,  231 \u2212 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.<\/p>\n<pre class=\"highlight\"><code class=\"language-cpp line-numbers\">\nclass Solution {\npublic:\n    int reverse(int x) {\n        long long int sign = x &lt; 0 ? -1 : 1;\n        long long int count = 1;\n        long long int tmp = (long long int)x * sign;\n        long long int base = 1;\n        long long int res = 0;\n        while (tmp &gt; 0) {\n            count *= 10;\n            tmp \/= 10;\n        }\n        count \/= 10;\n        tmp = (long long int)x * sign;\n        while (tmp &gt; 0) {\n            res += tmp \/ count * base;\n            tmp -= (tmp \/ count) * count;\n            count \/= 10;\n            base *= 10;\n        }\n\n        res *= sign;\n        if (res &gt; INT32_MAX) {\n            res = 0;\n        }\n        if (res &lt; INT32_MIN) {\n            res = 0;\n        }\n\n        return res;\n    }\n};\n<\/code><\/pre>\n<hr>\n<p><strong><em>8. String to Integer (atoi)<\/em><\/strong><\/p>\n<p>Implement atoi which converts a string to an integer.<\/p>\n<p>The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.<\/p>\n<p>The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.<\/p>\n<p>If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.<\/p>\n<p>If no valid conversion could be performed, a zero value is returned.<\/p>\n<p>Note:<\/p>\n<p>Only the space character &#8216; &#8216; is considered as whitespace character.<br \/>\nAssume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [\u22122^31,  2^31 \u2212 1]. If the numerical value is out of the range of representable values, INT_MAX (2^31 \u2212 1) or INT_MIN (\u22122^31) is returned.<\/p>\n<p><strong>Example 1:<\/strong><br \/>\nInput: &#8220;42&#8221;<br \/>\nOutput: 42<\/p>\n<p><strong>Example 2:<\/strong><br \/>\nInput: &#8221;   -42&#8243;<br \/>\nOutput: -42<br \/>\nExplanation: The first non-whitespace character is &#8216;-&#8216;, which is the minus sign.<br \/>\nThen take as many numerical digits as possible, which gets 42.<\/p>\n<p><strong>Example 3:<\/strong><br \/>\nInput: &#8220;4193 with words&#8221;<br \/>\nOutput: 4193<br \/>\nExplanation: Conversion stops at digit &#8216;3&#8217; as the next character is not a numerical digit.<\/p>\n<p><strong>Example 4:<\/strong><br \/>\nInput: &#8220;words and 987&#8221;<br \/>\nOutput: 0<br \/>\nExplanation: The first non-whitespace character is &#8216;w&#8217;, which is not a numerical<br \/>\ndigit or a +\/- sign. Therefore no valid conversion could be performed.<\/p>\n<p><strong>Example 5:<\/strong><br \/>\nInput: &#8220;-91283472332&#8221;<br \/>\nOutput: -2147483648<br \/>\nExplanation: The number &#8220;-91283472332&#8221; is out of the range of a 32-bit signed integer.<br \/>\nThefore INT_MIN (\u2212231) is returned.<\/p>\n<pre class=\"highlight\"><code class=\"language-cpp line-numbers\">\nclass Solution {\npublic:\n    int myAtoi(string str) {\n        long ans = 0;\n        bool tag = true;\n        for (int i = 0; i &lt; str.length(); ) {\n            \/\/\u8df3\u8fc7\u6240\u6709\u5148\u5bfc\u7a7a\u683c\n            while (str[i] == &#039; &#039;) {\n                ++i;\n            }\n            \/\/\u6807\u8bb0\u6b63\u8d1f\u53f7\n            if (str[i] == &#039;-&#039; || str[i] == &#039;+&#039;) {\n                tag = (str[i] == &#039;-&#039;) ? false : true;\n                ++i;\n            }\n            \/\/\u4e0d\u7528\u5904\u7406\u5176\u4ed6\u7b26\u53f7,\u53d1\u73b0\u65e0\u6548\u7b26\u53f7\u76f4\u63a5\u7ed3\u675f\n            while (str[i] &gt;= &#039;0&#039; &amp;&amp; str[i] &lt;= &#039;9&#039;) {\n                ans = ans * 10 + (str[i] - &#039;0&#039;);\n                \/\/\u51cf\u679d\n                if (tag &amp;&amp; ans &gt;= INT_MAX) {\n                    return INT_MAX;\n                }\n                if (!tag &amp;&amp; -ans &lt;= INT_MIN) {\n                    return INT_MIN;\n                }\n                ++i;\n            }\n            return (tag ? ans : -ans);\n        }\n        return (tag ? ans : -ans);\n    }\n};\n<\/code><\/pre>\n<hr>\n<p><strong><em>9. Palindrome Number<\/em><\/strong><br \/>\nDetermine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.<\/p>\n<p><strong>Example 1:<\/strong><br \/>\nInput: 121<br \/>\nOutput: true<\/p>\n<p><strong>Example 2:<\/strong><br \/>\nInput: -121<br \/>\nOutput: false<br \/>\nExplanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.<\/p>\n<p><strong>Example 3:<\/strong><br \/>\nInput: 10<br \/>\nOutput: false<br \/>\nExplanation: Reads 01 from right to left. Therefore it is not a palindrome.<\/p>\n<pre class=\"highlight\"><code class=\"language-cpp line-numbers\">\nclass Solution {\npublic:\n    bool isPalindrome(int x) {\n        if (x &lt; 0) {\n            return false;\n        }\n        long long int L = x;\n        long long int R = 0;\n        long long int count = 0;\n        while (x) {\n            R = R * 10 + x % 10;\n            if (R &gt; INT_MAX) return false;\n            x \/= 10;\n        }\n\n        return (L == R);\n    }\n};\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>1,517 Views1. Two Sum Given an array of integers, retur [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-924","post","type-post","status-publish","format-standard","hentry","category-lc"],"_links":{"self":[{"href":"http:\/\/www.mrtblog.cn\/index.php?rest_route=\/wp\/v2\/posts\/924","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.mrtblog.cn\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.mrtblog.cn\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.mrtblog.cn\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/www.mrtblog.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=924"}],"version-history":[{"count":24,"href":"http:\/\/www.mrtblog.cn\/index.php?rest_route=\/wp\/v2\/posts\/924\/revisions"}],"predecessor-version":[{"id":1011,"href":"http:\/\/www.mrtblog.cn\/index.php?rest_route=\/wp\/v2\/posts\/924\/revisions\/1011"}],"wp:attachment":[{"href":"http:\/\/www.mrtblog.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=924"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.mrtblog.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=924"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.mrtblog.cn\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=924"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}