<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>reverse Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/reverse/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/reverse/</link>
	<description></description>
	<lastBuildDate>Sun, 30 Jan 2022 16:03:07 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>reverse Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/reverse/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2139. Minimum Moves to Reach Target Score</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2139-minimum-moves-to-reach-target-score/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2139-minimum-moves-to-reach-target-score/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 30 Jan 2022 16:00:45 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[reverse]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9435</guid>

					<description><![CDATA[<p>You are playing a game with integers. You start with the integer&#160;1&#160;and you want to reach the integer&#160;target. In one move, you can either: Increment&#160;the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-2139-minimum-moves-to-reach-target-score/">花花酱 LeetCode 2139. Minimum Moves to Reach Target Score</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are playing a game with integers. You start with the integer&nbsp;<code>1</code>&nbsp;and you want to reach the integer&nbsp;<code>target</code>.</p>



<p>In one move, you can either:</p>



<ul><li><strong>Increment</strong>&nbsp;the current integer by one (i.e.,&nbsp;<code>x = x + 1</code>).</li><li><strong>Double</strong>&nbsp;the current integer (i.e.,&nbsp;<code>x = 2 * x</code>).</li></ul>



<p>You can use the&nbsp;<strong>increment</strong>&nbsp;operation&nbsp;<strong>any</strong>&nbsp;number of times, however, you can only use the&nbsp;<strong>double</strong>&nbsp;operation&nbsp;<strong>at most</strong>&nbsp;<code>maxDoubles</code>&nbsp;times.</p>



<p>Given the two integers&nbsp;<code>target</code>&nbsp;and&nbsp;<code>maxDoubles</code>, return&nbsp;<em>the minimum number of moves needed to reach&nbsp;</em><code>target</code><em>&nbsp;starting with&nbsp;</em><code>1</code>.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> target = 5, maxDoubles = 0
<strong>Output:</strong> 4
<strong>Explanation:</strong> Keep incrementing by 1 until you reach target.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> target = 19, maxDoubles = 2
<strong>Output:</strong> 7
<strong>Explanation:</strong> Initially, x = 1
Increment 3 times so x = 4
Double once so x = 8
Increment once so x = 9
Double again so x = 18
Increment once so x = 19
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> target = 10, maxDoubles = 4
<strong>Output:</strong> 4
<strong>Explanation:</strong>Initially, x = 1
Increment once so x = 2
Double once so x = 4
Increment once so x = 5
Double again so x = 10
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li><li><code>0 &lt;= maxDoubles &lt;= 100</code></li></ul>



<h2><strong>Solution: Reverse + Greedy</strong></h2>



<p>If num is odd, decrement it by 1. Divide num by 2 until maxdoubles times. Apply decrementing until 1 reached.</p>



<p>ex1: 19 (dec)-> 18 (div1)-> 9 (dec) -> 8 (div2)-> 4 <meta charset="utf-8">(dec)-> 3 <meta charset="utf-8">(dec)-> 2 <meta charset="utf-8">(dec)-> 1</p>



<p>Time complexity: O(logn)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int minMoves(int target, int maxDoubles) {
    int ans = 0;
    while (maxDoubles-- &amp;&amp; target != 1) {
      if (target &amp; 1)
        --target, ++ans;
      ++ans;
      target &gt;&gt;= 1;      
    }
    ans += (target - 1);
    return ans;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-2139-minimum-moves-to-reach-target-score/">花花酱 LeetCode 2139. Minimum Moves to Reach Target Score</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-2139-minimum-moves-to-reach-target-score/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2130. Maximum Twin Sum of a Linked List</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-2130-maximum-twin-sum-of-a-linked-list/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-2130-maximum-twin-sum-of-a-linked-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 09 Jan 2022 11:40:22 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[reverse]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9415</guid>

					<description><![CDATA[<p>In a linked list of size&#160;n, where&#160;n&#160;is&#160;even, the&#160;ith&#160;node (0-indexed) of the linked list is known as the&#160;twin&#160;of the&#160;(n-1-i)th&#160;node, if&#160;0 &#60;= i &#60;= (n / 2)&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-2130-maximum-twin-sum-of-a-linked-list/">花花酱 LeetCode 2130. Maximum Twin Sum of a Linked List</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In a linked list of size&nbsp;<code>n</code>, where&nbsp;<code>n</code>&nbsp;is&nbsp;<strong>even</strong>, the&nbsp;<code>i<sup>th</sup></code>&nbsp;node (<strong>0-indexed</strong>) of the linked list is known as the&nbsp;<strong>twin</strong>&nbsp;of the&nbsp;<code>(n-1-i)<sup>th</sup></code>&nbsp;node, if&nbsp;<code>0 &lt;= i &lt;= (n / 2) - 1</code>.</p>



<ul><li>For example, if&nbsp;<code>n = 4</code>, then node&nbsp;<code>0</code>&nbsp;is the twin of node&nbsp;<code>3</code>, and node&nbsp;<code>1</code>&nbsp;is the twin of node&nbsp;<code>2</code>. These are the only nodes with twins for&nbsp;<code>n = 4</code>.</li></ul>



<p>The&nbsp;<strong>twin sum&nbsp;</strong>is defined as the sum of a node and its twin.</p>



<p>Given the&nbsp;<code>head</code>&nbsp;of a linked list with even length, return&nbsp;<em>the&nbsp;<strong>maximum twin sum</strong>&nbsp;of the linked list</em>.</p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/12/03/eg1drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [5,4,2,1]
<strong>Output:</strong> 6
<strong>Explanation:</strong>
Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.
There are no other nodes with twins in the linked list.
Thus, the maximum twin sum of the linked list is 6. 
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/12/03/eg2drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [4,2,2,3]
<strong>Output:</strong> 7
<strong>Explanation:</strong>
The nodes with twins present in this linked list are:
- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.
- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.
Thus, the maximum twin sum of the linked list is max(7, 4) = 7. 
</pre>



<p><strong>Example 3:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/12/03/eg3drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1,100000]
<strong>Output:</strong> 100001
<strong>Explanation:</strong>
There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li>The number of nodes in the list is an&nbsp;<strong>even</strong>&nbsp;integer in the range&nbsp;<code>[2, 10<sup>5</sup>]</code>.</li><li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li></ul>



<h2><strong>Solution: Two Pointers + Reverse List</strong></h2>



<p>Use fast slow pointers to find the middle point and reverse the second half.</p>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int pairSum(ListNode* head) {
    auto reverse = [](ListNode* head, ListNode* prev = nullptr) {
      while (head) {
        swap(head-&gt;next, prev);
        swap(head, prev);
      }
      return prev;
    };
    
    ListNode* fast = head;
    ListNode* slow = head;
    while (fast) {
      fast = fast-&gt;next-&gt;next;
      slow = slow-&gt;next;
    }
    
    slow = reverse(slow);
    int ans = 0;
    while (slow) {
      ans = max(ans, head-&gt;val + slow-&gt;val);
      head = head-&gt;next;
      slow = slow-&gt;next;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-2130-maximum-twin-sum-of-a-linked-list/">花花酱 LeetCode 2130. Maximum Twin Sum of a Linked List</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-2130-maximum-twin-sum-of-a-linked-list/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 143. Reorder List</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-143-reorder-list/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-143-reorder-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 29 Nov 2021 07:08:40 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[fast slow]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[reverse]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8926</guid>

					<description><![CDATA[<p>You are given the head of a singly linked-list. The list can be represented as: L0 → L1 → … → Ln - 1 →&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-143-reorder-list/">花花酱 LeetCode 143. Reorder List</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given the head of a singly linked-list. The list can be represented as:</p>



<pre class="wp-block-preformatted;crayon:false">L<sub>0</sub> → L<sub>1</sub> → … → L<sub>n - 1</sub> → L<sub>n</sub>
</pre>



<p><em>Reorder the list to be on the following form:</em></p>



<pre class="wp-block-preformatted;crayon:false">L<sub>0</sub> → L<sub>n</sub> → L<sub>1</sub> → L<sub>n - 1</sub> → L<sub>2</sub> → L<sub>n - 2</sub> → …
</pre>



<p>You may not modify the values in the list&#8217;s nodes. Only nodes themselves may be changed.</p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/03/04/reorder1linked-list.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1,2,3,4]
<strong>Output:</strong> [1,4,2,3]
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/03/09/reorder2-linked-list.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1,2,3,4,5]
<strong>Output:</strong> [1,5,2,4,3]
</pre>



<p><strong>Constraints:</strong></p>



<ul><li>The number of nodes in the list is in the range&nbsp;<code>[1, 5 * 10<sup>4</sup>]</code>.</li><li><code>1 &lt;= Node.val &lt;= 1000</code></li></ul>



<h2><strong>Solution: Three steps</strong></h2>



<p>Step 1: Find mid node that splits the list into two halves.<br>Step 2: Reverse the second half<br>Step 3: Merge two lists</p>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  void reorderList(ListNode* head) {
    if (!head || !head-&gt;next) return;
    ListNode* slow = head;
    ListNode* fast = head;            

    while (fast-&gt;next &amp;&amp; fast-&gt;next-&gt;next) {
      slow = slow-&gt;next;
      fast = fast-&gt;next-&gt;next;          
    }
    
    ListNode* h1 = head;
    ListNode* h2 = reverse(slow-&gt;next);
    slow-&gt;next = nullptr;

    while (h1 &amp;&amp; h2) {
      ListNode* n1 = h1-&gt;next;
      ListNode* n2 = h2-&gt;next;
      h1-&gt;next = h2;
      h2-&gt;next = n1;
      h1 = n1;
      h2 = n2;
    }
  }
private:       
  // reverse a linked list
  // returns head of the linked list
  ListNode* reverse(ListNode* head) {
    if (!head || !head-&gt;next) return head;

    ListNode* prev = head;
    ListNode* cur = head-&gt;next;
    ListNode* next = cur;
    while (cur) {
      next = next-&gt;next;
      cur-&gt;next = prev;
      prev = cur;
      cur = next;
    }

    head-&gt;next = nullptr;
    return prev;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-143-reorder-list/">花花酱 LeetCode 143. Reorder List</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-143-reorder-list/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 151. Reverse Words in a String</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-151-reverse-words-in-a-string/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-151-reverse-words-in-a-string/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Nov 2021 21:45:14 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[reverse]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8866</guid>

					<description><![CDATA[<p>Given an input string&#160;s, reverse the order of the&#160;words. A&#160;word&#160;is defined as a sequence of non-space characters. The&#160;words&#160;in&#160;s&#160;will be separated by at least one space.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-151-reverse-words-in-a-string/">花花酱 LeetCode 151. Reverse Words in a String</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given an input string&nbsp;<code>s</code>, reverse the order of the&nbsp;<strong>words</strong>.</p>



<p>A&nbsp;<strong>word</strong>&nbsp;is defined as a sequence of non-space characters. The&nbsp;<strong>words</strong>&nbsp;in&nbsp;<code>s</code>&nbsp;will be separated by at least one space.</p>



<p>Return&nbsp;<em>a string of the words in reverse order concatenated by a single space.</em></p>



<p><strong>Note</strong>&nbsp;that&nbsp;<code>s</code>&nbsp;may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "the sky is blue"
<strong>Output:</strong> "blue is sky the"
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "  hello world  "
<strong>Output:</strong> "world hello"
<strong>Explanation:</strong> Your reversed string should not contain leading or trailing spaces.
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "a good   example"
<strong>Output:</strong> "example good a"
<strong>Explanation:</strong> You need to reduce multiple spaces between two words to a single space in the reversed string.
</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "  Bob    Loves  Alice   "
<strong>Output:</strong> "Alice Loves Bob"
</pre>



<p><strong>Example 5:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "Alice does not even like bob"
<strong>Output:</strong> "bob like even not does Alice"
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li><li><code>s</code>&nbsp;contains English letters (upper-case and lower-case), digits, and spaces&nbsp;<code>' '</code>.</li><li>There is&nbsp;<strong>at least one</strong>&nbsp;word in&nbsp;<code>s</code>.</li></ul>



<p><strong>Follow-up:&nbsp;</strong>If the string data type is mutable in your language, can&nbsp;you solve it&nbsp;<strong>in-place</strong>&nbsp;with&nbsp;<code>O(1)</code>&nbsp;extra space?</p>



<h2><strong>Solution: Stack</strong></h2>



<p>Time complexity: O(n)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  string reverseWords(string s) {
    stringstream ss(s);
    stack&lt;string&gt; st;
    string w;
    while (ss &gt;&gt; w)
      st.push(w);
    string ans;
    while (!st.empty()) {
      ans += st.top();
      st.pop();
      if (!st.empty()) ans += ' ';
    }
    return ans;
  }
};</pre>
</div></div>



<h2><strong>Solution: In-Place</strong></h2>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  string reverseWords(string&amp; s) {
    reverse(begin(s), end(s));
    int l = 0;
    for (int i = 0, j = 0; i &lt; s.length(); ++i) {
      if (s[i] == ' ') continue;
      if (l) ++l;
      j = i;
      while (j &lt; s.length() &amp;&amp; s[j] != ' ') ++j;
      reverse(begin(s) + l, begin(s) + j);
      l += (j - i);
      i = j;
    }
    s.resize(l);
    return s;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-151-reverse-words-in-a-string/">花花酱 LeetCode 151. Reverse Words in a String</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-151-reverse-words-in-a-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1330. Reverse Subarray To Maximize Array Value</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1330-reverse-subarray-to-maximize-array-value/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1330-reverse-subarray-to-maximize-array-value/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 26 Jan 2020 17:44:37 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[reverse]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6135</guid>

					<description><![CDATA[<p>You are given an integer array&#160;nums. The&#160;value&#160;of this array is defined as the sum of&#160;&#124;nums[i]-nums[i+1]&#124;&#160;for all&#160;0 &#60;= i &#60; nums.length-1. You are allowed to select&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1330-reverse-subarray-to-maximize-array-value/">花花酱 LeetCode 1330. Reverse Subarray To Maximize Array Value</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given an integer array&nbsp;<code>nums</code>. The&nbsp;<em>value</em>&nbsp;of this array is defined as the sum of&nbsp;<code>|nums[i]-nums[i+1]|</code>&nbsp;for all&nbsp;<code>0 &lt;= i &lt; nums.length-1</code>.</p>



<p>You are allowed to select any subarray of the given array and reverse it. You can perform this operation&nbsp;<strong>only once</strong>.</p>



<p>Find maximum possible value of the final array.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,3,1,5,4]
<strong>Output:</strong> 10
<strong>Explanation: </strong>By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,4,9,24,2,1,10]
<strong>Output:</strong> 68
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= nums.length &lt;= 3*10^4</code></li><li><code>-10^5 &lt;= nums[i] &lt;= 10^5</code></li></ul>



<h2><strong>Solution: Greedy</strong></h2>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maxValueAfterReverse(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    int sum = 0;
    int gain = 0;    
    int hi = INT_MIN;
    int lo = INT_MAX;
    for (int i = 0; i &lt; n - 1; ++i) {
      int n1 = nums[i];
      int n2 = nums[i + 1];
      sum += abs(n1 - n2);
      gain = max({gain, 
                 abs(nums[0] - n2) - abs(n1 - n2),
                 abs(nums[n - 1] - n1) - abs(n1 - n2)});
      hi = max(hi, min(n1, n2));
      lo = min(lo, max(n1, n2));
    }
    return sum + max(gain, (hi - lo) * 2);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1330-reverse-subarray-to-maximize-array-value/">花花酱 LeetCode 1330. Reverse Subarray To Maximize Array Value</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-1330-reverse-subarray-to-maximize-array-value/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 190. Reverse Bits</title>
		<link>https://zxi.mytechroad.com/blog/bit/leetcode-190-reverse-bits/</link>
					<comments>https://zxi.mytechroad.com/blog/bit/leetcode-190-reverse-bits/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 30 Sep 2019 08:32:29 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[O(1)]]></category>
		<category><![CDATA[reverse]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5646</guid>

					<description><![CDATA[<p>Reverse bits of a given 32 bits unsigned integer. Example 1: Input: 00000010100101000001111010011100 Output: 00111001011110000010100101000000 Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-190-reverse-bits/">花花酱 LeetCode 190. Reverse Bits</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 190. Reverse Bits - 刷题找工作 EP284" width="500" height="375" src="https://www.youtube.com/embed/K0EHvvbUdEg?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Reverse bits of a given 32 bits unsigned integer.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> 00000010100101000001111010011100
<strong>Output:</strong> 00111001011110000010100101000000
<strong>Explanation: </strong>The input binary string <strong>00000010100101000001111010011100</strong> represents the unsigned integer 43261596, so return 964176192 which its binary representation is <strong>00111001011110000010100101000000</strong>.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> 11111111111111111111111111111101
<strong>Output:</strong> 10111111111111111111111111111111
<strong>Explanation: </strong>The input binary string <strong>11111111111111111111111111111101</strong> represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is <strong>10101111110010110010011101101001</strong>.</pre>



<p><strong>Note:</strong></p>



<ul><li>Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.</li><li>In Java,&nbsp;the compiler represents the signed integers using&nbsp;<a href="https://en.wikipedia.org/wiki/Two%27s_complement" target="_blank" rel="noreferrer noopener">2&#8217;s complement notation</a>. Therefore, in&nbsp;<strong>Example 2</strong>&nbsp;above the input represents the signed integer&nbsp;<code>-3</code>&nbsp;and the output represents the signed integer&nbsp;<code>-1073741825</code>.</li></ul>



<p><strong>Follow up</strong>:</p>



<p>If this function is called many times, how would you optimize it?</p>



<p>Solution: Bit operation</p>



<p>Time complexity: O(1)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  uint32_t reverseBits(uint32_t n) {
    uint32_t ans = 0;
    for (int i = 0; i &lt; 32; ++i) {
      ans &lt;&lt;= 1;
      ans |= n &amp; 1;      
      n &gt;&gt;= 1;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-190-reverse-bits/">花花酱 LeetCode 190. Reverse Bits</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/bit/leetcode-190-reverse-bits/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-1190-reverse-substrings-between-each-pair-of-parentheses/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-1190-reverse-substrings-between-each-pair-of-parentheses/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 Sep 2019 22:16:24 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(n^2)]]></category>
		<category><![CDATA[reverse]]></category>
		<category><![CDATA[stack]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5550</guid>

					<description><![CDATA[<p>Given a string&#160;s&#160;that consists of lower case English letters and brackets.&#160; Reverse the strings&#160;in each&#160;pair of matching parentheses, starting&#160;from the innermost one. Your result should&#160;not&#160;contain&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1190-reverse-substrings-between-each-pair-of-parentheses/">花花酱 LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a string&nbsp;<code>s</code>&nbsp;that consists of lower case English letters and brackets.&nbsp;</p>



<p>Reverse the strings&nbsp;in each&nbsp;pair of matching parentheses, starting&nbsp;from the innermost one.</p>



<p>Your result should&nbsp;<strong>not</strong>&nbsp;contain any bracket.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "(abcd)"
<strong>Output:</strong> "dcba"
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "(u(love)i)"
<strong>Output:</strong> "iloveu"
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "(ed(et(oc))el)"
<strong>Output:</strong> "leetcode"
</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "a(bcdefghijkl(mno)p)q"
<strong>Output:</strong> "apmnolkjihgfedcbq"
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>0 &lt;= s.length &lt;= 2000</code></li><li><code>s</code>&nbsp;only contains lower case English characters and parentheses.</li><li>It&#8217;s guaranteed that all parentheses are balanced.</li></ul>



<h2><strong>Solution: Stack</strong></h2>



<p>Use a stack of strings to track all the active strings.<br>Iterate over the input string:<br>1. Whenever there is a &#8216;(&#8216;, push an empty string to the stack.<br>2. Whenever this is a &#8216;)&#8217;, pop the top string and append the reverse of it to the new stack top.<br>3. Otherwise, append the letter to the string on top the of stack.<br><br>Once done, the (only) string on the top of the stack is the answer.</p>



<p>Time complexity: O(n^2)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  string reverseParentheses(string s) {
    stack&lt;string&gt; st;
    st.push(&quot;&quot;);
    for (char c : s) {
      if (c == '(') st.push(&quot;&quot;);
      else if (c != ')') st.top() += c;
      else {
        string t = st.top(); st.pop();
        st.top().insert(end(st.top()), rbegin(t), rend(t));
      }
    }
    return st.top();
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1190-reverse-substrings-between-each-pair-of-parentheses/">花花酱 LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/stack/leetcode-1190-reverse-substrings-between-each-pair-of-parentheses/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 92. Reverse Linked List II</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-92-reverse-linked-list-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-92-reverse-linked-list-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 24 Aug 2019 18:20:34 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[reverse]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5484</guid>

					<description><![CDATA[<p>Reverse a linked list from position&#160;m&#160;to&#160;n. Do it in one-pass. Note:&#160;1 ≤&#160;m&#160;≤&#160;n&#160;≤ length of list. Example: Input: 1-&#62;2-&#62;3-&#62;4-&#62;5-&#62;NULL, m = 2, n = 4 Output:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-92-reverse-linked-list-ii/">花花酱 LeetCode 92. Reverse Linked List II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Reverse a linked list from position&nbsp;<em>m</em>&nbsp;to&nbsp;<em>n</em>. Do it in one-pass.</p>



<p><strong>Note:&nbsp;</strong>1 ≤&nbsp;<em>m</em>&nbsp;≤&nbsp;<em>n</em>&nbsp;≤ length of list.</p>



<p><strong>Example:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL, <em>m</em> = 2, <em>n</em> = 4
<strong>Output:</strong> 1-&gt;4-&gt;3-&gt;2-&gt;5-&gt;NULL</pre>



<p><strong>Solution: </strong></p>



<ol><li>Store the m &#8211; 1 and m-th item as prev and tail before reversing</li><li>Reverse the m to n, return the head and tail-&gt;next of the reversed list</li><li>Reconnect prev and head, tail and tail-&gt;next</li></ol>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  ListNode* reverseBetween(ListNode* head, int m, int n) {
    ListNode dummy(0);
    dummy.next = head;
    ListNode* p = &amp;dummy;
    // Find the m-1 th node
    for (int i = 0; i &lt; m - 1; ++i) 
      p = p-&gt;next;
    ListNode* prev = p;
    ListNode* curr = p-&gt;next;
    ListNode* tail = curr;    
    // Reverse from m to n
    for (int i = m; i &lt;= n; ++i) {
      ListNode* next = curr-&gt;next;
      curr-&gt;next = prev;
      prev = curr;
      curr = next;
    }    
    //  Connect three parts
    p-&gt;next = prev;
    tail-&gt;next = curr;
    return dummy.next;
  }
};</pre>

</div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def reverseBetween(self, head: ListNode, m: int, n: int) -&gt; ListNode:
    dummy = ListNode(0)
    dummy.next = head
    p = dummy
    for i in range(m - 1):
      p = p.next
    prev = p
    curr = p.next
    tail = curr
    for i in range(n - m + 1):
      next = curr.next
      curr.next = prev
      prev = curr
      curr = next
    p.next = prev
    tail.next = curr
    return dummy.next</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-92-reverse-linked-list-ii/">花花酱 LeetCode 92. Reverse Linked List II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-92-reverse-linked-list-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 917. Reverse Only Letters</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-917-reverse-only-letters/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-917-reverse-only-letters/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 07 Oct 2018 03:43:41 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[reverse]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4157</guid>

					<description><![CDATA[<p>Problem Given a string S, return the &#8220;reversed&#8221; string where all characters that are not a letter stay in the same place, and all letters reverse their&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-917-reverse-only-letters/">花花酱 LeetCode 917. Reverse Only Letters</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Given a string <code>S</code>, return the &#8220;reversed&#8221; string where all characters that are not a letter stay in the same place, and all letters reverse their positions.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-1-1">"ab-cd"</span>
<strong>Output: </strong><span id="example-output-1">"dc-ba"</span>
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-2-1">"a-bC-dEf-ghIj"</span>
<strong>Output: </strong><span id="example-output-2">"j-Ih-gfE-dCba"</span>
</pre>
<p><strong>Example 3:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-3-1">"Test1ng-Leet=code-Q!"</span>
<strong>Output: </strong><span id="example-output-3">"Qedo1ct-eeLg=ntse-T!"</span>
</pre>
<p><strong>Note:</strong></p>
<ol>
<li><code>S.length &lt;= 100</code></li>
<li><code>33 &lt;= S[i].ASCIIcode &lt;= 122</code></li>
<li><code>S</code> doesn&#8217;t contain <code>\</code> or <code>"</code></li>
</ol>
<h1><strong>Solution: Two Pointers</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1) &#8211; in place</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++/index</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  string reverseOnlyLetters(string S) {
    int i = 0;
    int j = S.length() - 1;
    while (i &lt; j) {
      if (isalpha(S[i]) &amp;&amp; isalpha(S[j])) {
        swap(S[i++], S[j--]);        
      } else {
        if (!isalpha(S[i])) ++i;
        if (!isalpha(S[j])) --j;
      }
    }
    return S;
  }
};</pre><p></div><h2 class="tabtitle">C++/iter</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  string reverseOnlyLetters(string S) {
    auto it1 = begin(S);
    auto it2 = prev(end(S));
    while (it1 &lt; it2) {
      if (isalpha(*it1) &amp;&amp; isalpha(*it2)) {
        swap(*it1++, *it2--);
      } else {
        if (!isalpha(*it1)) ++it1;
        if (!isalpha(*it2)) --it2;
      }
    }
    return S;
  }
};</pre><p></div></div></p>
<p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-917-reverse-only-letters/">花花酱 LeetCode 917. Reverse Only Letters</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-917-reverse-only-letters/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 31. Next Permutation</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-31-next-permutation/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-31-next-permutation/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 03 Oct 2018 02:28:58 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[in place]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[permutation]]></category>
		<category><![CDATA[reverse]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4146</guid>

					<description><![CDATA[<p>Problem Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-31-next-permutation/">花花酱 LeetCode 31. Next Permutation</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Implement <strong>next permutation</strong>, which rearranges numbers into the lexicographically next greater permutation of numbers.</p>
<p>If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).</p>
<p>The replacement must be <strong><a href="http://en.wikipedia.org/wiki/In-place_algorithm" target="_blank" rel="noopener">in-place</a></strong> and use only constant extra memory.</p>
<p>Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.</p>
<p><code>1,2,3</code> → <code>1,3,2</code><br />
<code>3,2,1</code> → <code>1,2,3</code><br />
<code>1,1,5</code> → <code>1,5,1</code></p>
<h1><strong>Solution</strong></h1>
<p>Find the last acceding element x, swap with the smallest number y, y is after x that and y is greater than x.</p>
<p>Reverse the elements after x.</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, 8 ms
class Solution {
public:
  void nextPermutation(vector&lt;int&gt;&amp; nums) {
    int i = nums.size() - 2;
    while (i &gt;= 0 &amp;&amp; nums[i + 1] &lt;= nums[i]) --i;
    if (i &gt;= 0) {
      int j = nums.size() - 1;
      while (j &gt;= 0 &amp;&amp; nums[j] &lt;= nums[i]) --j;
      swap(nums[i], nums[j]);
    }
    reverse(begin(nums) + i + 1, end(nums));
  }
};</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag"># Author: Huahua, 48 ms
class Solution:
  def nextPermutation(self, nums):
    n = len(nums)
    i = n - 2
    while i &gt;= 0 and nums[i] &gt;= nums[i + 1]: i -= 1
    if i &gt;= 0:
      j = n - 1
      while j &gt;= 0 and nums[j] &lt;= nums[i]: j -= 1
      nums[i], nums[j] = nums[j], nums[i]
    nums[i + 1:] = nums[i+1:][::-1]</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-31-next-permutation/">花花酱 LeetCode 31. Next Permutation</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-31-next-permutation/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 7. Reverse Integer</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-7-reverse-integer/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-7-reverse-integer/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 12 Sep 2018 16:14:16 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[reverse]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3927</guid>

					<description><![CDATA[<p>Problem Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-7-reverse-integer/">花花酱 LeetCode 7. Reverse Integer</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Given a 32-bit signed integer, reverse digits of an integer.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> 123
<strong>Output:</strong> 321
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> -123
<strong>Output:</strong> -321
</pre>
<p><strong>Example 3:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> 120
<strong>Output:</strong> 21
</pre>
<p><strong>Note:</strong><br />
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2<sup>31</sup>,  2<sup>31 </sup>− 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.</p>
<h1><strong>Solution: Simulation</strong></h1>
<p>Reverse digit by digit. Be careful about the overflow and negative numbers (especially in Python)</p>
<p>Time complexity: O(log(x)) ~ O(1)</p>
<p>Space complexity: O(log(x)) ~ O(1)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int reverse(int x) {
    int ans = 0;
    while (x != 0) {
      int r = x % 10;
      if (ans &gt; INT_MAX / 10 || ans &lt; INT_MIN / 10) return 0;
      ans = ans * 10 + r;
      x /= 10;
    }
    return ans;
  }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">class Solution {
  public int reverse(int x) {
    int ans = 0;
    while (x != 0) {
      int r = x % 10;
      if (ans &gt; Integer.MAX_VALUE / 10 || ans &lt; Integer.MIN_VALUE / 10) return 0;
      ans = ans * 10 + r;
      x /= 10;
    }
    return ans;
  }
}</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">class Solution:
  def reverse(self, x):
    min_val = -(2**31);
    max_val = 2**31 - 1;
    sign = -1 if x &lt; 0 else 1
    x = abs(x)
    ans = 0
    while x != 0:            
      ans = ans * 10 + (x % 10)
      x //= 10
    ans *= sign
    if ans &gt; max_val or ans &lt; min_val: return 0
    return ans</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-7-reverse-integer/">花花酱 LeetCode 7. Reverse Integer</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-7-reverse-integer/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 189. Rotate Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-189-rotate-array/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-189-rotate-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 06 Aug 2018 15:22:05 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[reverse]]></category>
		<category><![CDATA[rotation]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3456</guid>

					<description><![CDATA[<p>Problem Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: [1,2,3,4,5,6,7] and k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-189-rotate-array/">花花酱 LeetCode 189. Rotate Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Given an array, rotate the array to the right by <em>k</em> steps, where <em>k</em> is non-negative.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false "><strong>Input:</strong> [1,2,3,4,5,6,7] and k = 3 
<strong>Output:</strong> [5,6,7,1,2,3,4]
<strong>Explanation:</strong> rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] 
rotate 3 steps to the right: [5,6,7,1,2,3,4]</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input:</strong>[-1,-100,3,99] and k = 2 
<strong>Output:</strong> [3,99,-1,-100] 
<strong>Explanation:</strong> rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100]</pre>
<p><strong>Note:</strong></p>
<ul>
<li>Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.</li>
<li>Could you do it in-place with O(1) extra space?</li>
</ul>
<h1><strong>Solution 1: Simulate rotation with three reverses.</strong></h1>
<p>If k &gt;= n, rotating k times has the same effect as rotating k % n times.</p>
<p>[1,2,3,4,5,6,7], K = 3</p>
<p>[5,6,7,1,2,3,4]</p>
<p>We can simulate the rotation with three reverses.</p>
<ol>
<li>reverse the whole array O(n) [<strong><span style="color: #ff0000;">7,6,5</span></strong>,<strong><span style="color: #000080;">4,3,2,1</span></strong>]</li>
<li>reverse the left part 0 ~ k &#8211; 1 O(k) [5,6,7,<strong><span style="color: #000080;">4,3,2,1]</span></strong></li>
<li>reverse the right part k ~ n &#8211; 1 O(n-k) [5,6,7,1,2,3,4]</li>
</ol>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1) in-place</p>
<p>C++</p><pre class="crayon-plain-tag">class Solution {
public:
  void rotate(vector&lt;int&gt;&amp; nums, int k) {
    if (nums.empty()) return;
    k %= nums.size();
    if (k == 0) return;
    reverse(begin(nums), end(nums));
    reverse(begin(nums), begin(nums) + k);
    reverse(begin(nums) + k, end(nums));
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-189-rotate-array/">花花酱 LeetCode 189. Rotate Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-189-rotate-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 345. Reverse Vowels of a String</title>
		<link>https://zxi.mytechroad.com/blog/two-pointers/leetcode-345-reverse-vowels-of-a-string/</link>
					<comments>https://zxi.mytechroad.com/blog/two-pointers/leetcode-345-reverse-vowels-of-a-string/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 19 Jul 2018 08:05:44 +0000</pubDate>
				<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[reverse]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3220</guid>

					<description><![CDATA[<p>Problem Write a function that takes a string as input and reverse only the vowels of a string. Example 1: Given s = &#8220;hello&#8221;, return&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-345-reverse-vowels-of-a-string/">花花酱 LeetCode 345. Reverse Vowels of a String</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Write a function that takes a string as input and reverse only the vowels of a string.</p>
<p><b>Example 1:</b><br />
Given s = &#8220;hello&#8221;, return &#8220;holle&#8221;.</p>
<p><b>Example 2:</b><br />
Given s = &#8220;leetcode&#8221;, return &#8220;leotcede&#8221;.</p>
<p><b>Note:</b><br />
The vowels does not include the letter &#8220;y&#8221;.</p>
<h1><strong>Solution</strong></h1>
<p></p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 8 ms
class Solution {
public:
    string reverseVowels(string s) {
      int i = 0;
      int j = s.size() - 1;
      while (i &lt; j) {
        while (!isVowel(s[i]) &amp;&amp; i &lt; j) ++i;
        while (!isVowel(s[j]) &amp;&amp; i &lt; j) --j;                
        swap(s[i++], s[j--]);
      }
      return s;
    }
private:
  bool isVowel(char c) {
    c = tolower(c);
    return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-345-reverse-vowels-of-a-string/">花花酱 LeetCode 345. Reverse Vowels of a String</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/two-pointers/leetcode-345-reverse-vowels-of-a-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 541. Reverse String II</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-541-reverse-string-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-541-reverse-string-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 22 Mar 2018 05:10:55 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[reverse]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2282</guid>

					<description><![CDATA[<p>Problem 题目大意：把字符串分成块，每块长度2k，单独反转每一块的前k的字符。 https://leetcode.com/problems/reverse-string-ii/description/ Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-541-reverse-string-ii/">花花酱 LeetCode 541. Reverse String II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<div class="question-description">
<h1><strong>Problem</strong></h1>
<p>题目大意：把字符串分成块，每块长度2k，单独反转每一块的前k的字符。</p>
<p><a href="https://leetcode.com/problems/reverse-string-ii/description/">https://leetcode.com/problems/reverse-string-ii/description/</a></p>
<div>
<p>Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.<b>Example:</b></p>
<pre class="crayon:false "><b>Input:</b> s = "abcdefg", k = 2
<b>Output:</b> "bacdfeg"
</pre>
<p><b>Restrictions:</b></p>
<ol>
<li>The string consists of lower English letters only.</li>
<li>Length of the given string and k will in the range [1, 10000]</li>
</ol>
</div>
</div>
<h1><strong>Solution</strong></h1>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 9 ms
class Solution {
public:
  string reverseStr(string s, int k) {
    const int n = s.length();
    for (int i = 0; i &lt;= n / k; i += 2)      
      std::reverse(s.begin() + i * k, s.begin() + min(n, (i + 1) * k));
    return s;
  }
};</pre><p></p>
<h1><strong>Related Problems</strong></h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/string/leetcode-557-reverse-words-in-a-string-iii/">花花酱 LeetCode 557 Reverse Words in a String III</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-541-reverse-string-ii/">花花酱 LeetCode 541. Reverse String II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-541-reverse-string-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 206. Reverse Linked List</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-206-reverse-linked-list/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-206-reverse-linked-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 08 Mar 2018 16:44:14 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[curr]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[next]]></category>
		<category><![CDATA[prev]]></category>
		<category><![CDATA[reverse]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2044</guid>

					<description><![CDATA[<p>题目大意：反转一个单向链表 Problem: https://leetcode.com/problems/reverse-linked-list/description/ Reverse a singly linked list. Solution 1: Tracking prev / curr / next node Time complexity: O(n) Space complexity: O(1) C++ [crayon-663cab45cadbf661435003/]&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-206-reverse-linked-list/">花花酱 LeetCode 206. Reverse Linked List</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>题目大意：反转一个单向链表</p>
<p><strong>Problem:</strong></p>
<p><a href="https://leetcode.com/problems/reverse-linked-list/description/">https://leetcode.com/problems/reverse-linked-list/description/</a></p>
<p>Reverse a singly linked list.</p>
<p><strong>Solution 1:</strong></p>
<p>Tracking prev / curr / next node</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 9 ms
class Solution {
public:
  ListNode* reverseList(ListNode* head) {
    ListNode* prev = nullptr;
    ListNode* curr = head;
    ListNode* next;
    while (curr) {
      next = curr-&gt;next;
      curr-&gt;next = prev;
      prev = curr;
      curr = next;
    }
    return prev;
  }
};</pre><p>Java</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 0 ms
class Solution {
  public ListNode reverseList(ListNode head) {
    ListNode prev = null;
    ListNode curr = head;
    ListNode next;
    while (curr != null) {
      next = curr.next;
      curr.next = prev;
      prev = curr;
      curr = next;
    }
    return prev;
  }
}</pre><p>Python 3</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 48 ms
"""
class Solution:
  def reverseList(self, head):
    prev, curr, nxt = None, head, None;    
    while curr:
      nxt, curr.next = curr.next, prev      
      prev, curr = curr, nxt
    return prev</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-206-reverse-linked-list/">花花酱 LeetCode 206. Reverse Linked List</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-206-reverse-linked-list/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
