Why looping through the array backwards is not returning reversed array of strings until I assigned it to the original array?

huangapple go评论68阅读模式
英文:

Why looping through the array backwards is not returning reversed array of strings until I assigned it to the original array?

问题

以下是代码部分的中文翻译:

/**
 * @param {character[]} s
 * @return {void} 不要返回任何东西,而是在原地修改 s。
 */
var reverseString = function (s) {
    let reversed = [];

    for (let i = s.length - 1; i >= 0; i--) {
        reversed.push(s[i]);
    }

    for (let i = 0; i < s.length; i++) {
        s[i] = reversed[i];
    }

    return reversed;
};

请问还有其他需要帮助的地方吗?

英文:

So I was doing this coding problem and where you have yo return reversed array of strings.

/**
 * @param {character[]} s
 * @return {void} Do not return anything, modify s in-place instead.
 */
var reverseString = function (s) {

};

where s is an array of string.

Example<br>
Input: s = ["h","e","l","l","o"]<br>
Output: ["o","l","l","e","h"]

I have done this

/**
 * @param {character[]} s
 * @return {void} Do not return anything, modify s in-place instead.
 */
var reverseString = function (s) {
      let arr = [];

     for (let i = s.length-1;i &gt;= 0; i--){
         arr.push(s[i]);
     }
     return arr;
};

But this is the wrong solution. IDKW?

After I did this:

/**
 * @param {character[]} s
 * @return {void} Do not return anything, modify s in-place instead.
 */
var reverseString = function (s) {
    let reversed = [];

    for (let i = s.length - 1; i &gt;= 0; i--) {
        reversed.push(s[i]);
    }

    for (let i = 0; i &lt; s.length; i++) {
        s[i] = reversed[i];
    }

    return reversed;
};

It runs perfectly can you explain why the upper one is not executing correctly, why it is pushing the elements in the array as the original one instead of putting in reversing order.

答案1

得分: 1

在第一个示例中,您创建了一个新数组(arr = [])并将原始元素推入其中(arr.push(s[i])),而要求是修改原始数组本身("在原地修改 s")。

请注意,您的第二个示例有点不正确:它修改了原始数组(s[i] = reversed[i]),但返回了新数组(return reversed),而函数应该返回空(@return {void})。

var reverseString = function (s) {
    // 这创建了一个新数组
    let reversed = [];

    for (let i = s.length - 1; i &gt;= 0; i--) {
        // 这将原始元素反向推入新数组
        reversed.push(s[i]);
    }

    for (let i = 0; i &lt; s.length; i++) {
        // 这修改了原始数组
        s[i] = reversed[i];
    }

    // 但您返回了新数组
    return reversed;
};

数组有一个内置方法可以将其反转:Array#reverse()。它正好做到了您想要的:在原地反转数组。

function reverseArrayOfStrings(s) {
  s.reverse();
};

试一试:

<!-- 开始代码段: js 隐藏: true -->

<!-- 语言: lang-js -->
console.config({ maximize: true });

function reverseArrayOfStrings(s) {
  s.reverse();
};

const testcase = ['1', '2', '3'];
console.log(testcase);

reverseArrayOfStrings(testcase);
console.log(testcase);

<!-- 语言: lang-html -->
<script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

<!-- 结束代码段 -->

如果您想编写自己的方法,请继续阅读。

首先,我们创建一个中点并称其为 pivotpivot = Math.floor(s.length / 2)。它用作我们循环的停止点。然后,我们逐对交换元素:

原始:
┌───────────┬─────┬─────┬─────┬─────┬─────┐
│ 索引:      │  0  │  1  │  2  │  3  │  4  │
├───────────┼─────┼─────┼─────┼─────┼─────┤
│ 元素:      │ '1' │ '2' │ '3' │ '4' │ '5' │
└───────────┴─────┴─────┴─────┴─────┴─────┘

将索引为 0 的元素与索引为 4 的元素交换:
┌───────────┬─────┬─────┬─────┬─────┬─────┐
│ 索引:      │  0  │  1  │  2  │  3  │  4  │
├───────────┼─────┼─────┼─────┼─────┼─────┤
│ 元素:      │ '5' │ '2' │ '3' │ '4' │ '1' │
└───────────┴─────┴─────┴─────┴─────┴─────┘

将索引为 1 的元素与索引为 3 的元素交换:
┌───────────┬─────┬─────┬─────┬─────┬─────┐
│ 索引:      │  0  │  1  │  2  │  3  │  4  │
├───────────┼─────┼─────┼─────┼─────┼─────┤
│ 元素:      │ '5' │ '4' │ '3' │ '2' │ '1' │
└───────────┴─────┴─────┴─────┴─────┴─────┘

将索引为 2 的元素与自身交换(即无变化):
┌───────────┬─────┬─────┬─────┬─────┬─────┐
│ 索引:      │  0  │  1  │  2  │  3  │  4  │
├───────────┼─────┼─────┼─────┼─────┼─────┤
│ 元素:      │ '5' │ '4' │ '3' │ '2' │ '1' │
└───────────┴─────┴─────┴─────┴─────┴─────┘

让我们称一轮中要交换的索引为 xyx <= y)。x 从 0 开始,而 ys.length - 1 开始(5 - 4)。x 在每一轮增加 1,而 y 在同一轮内减少 1。这导致了一个公式:

y = s.length - x - 1

为了简化事情,我们循环从 0 到 pivot,包括 pivot。这使得 xindex 相同:

for (let index = 0, pivot = Math.floor(s.length / 2); index < pivot; index++) {
    // 这种语法称为“解构”。
    // 它将 s
展开收缩
的当前值分配给 s[index]
// 同时将 s[index] 的当前值分配给 s
展开收缩
,有效地交换它们的位置。
[s[index], s[s.length - index - 1]] = [s[s.length - index - 1], s[index]]; // 比较:
展开收缩
, s[y]] =
展开收缩
, s[x]];
}

试一试:

<!-- 开始代码段: js 隐藏: true 控制台: false Babel: false -->

<!-- 语言: lang-js -->
console.config({ maximize: true });

function reverseArrayOfStrings(s) {
  for (let index = 0, pivot = Math.floor(s.length / 2); index < pivot; index++) {
      //

<details>
<summary>英文:</summary>

In the first example you are creating a new array (`arr = []`) and push the original elements onto it (`arr.push(s[i])`), whereas the requirements is to modify the original array itself (&quot;*modify s in-place*&quot;).

Do note that your second example is a bit incorrect: It modifies the original array (`s[i] = reversed[i]`) yet it returns the new array (`return reversed`) whereas the function is supposed to return nothing (`@return {void}`).

```js
var reverseString = function (s) {
    // This creates a new array
    let reversed = [];

    for (let i = s.length - 1; i &gt;= 0; i--) {
        // This pushes the original elements onto the new array, backwards
        reversed.push(s[i]);
    }

    for (let i = 0; i &lt; s.length; i++) {
        // This modifies the original array
        s[i] = reversed[i];
    }

    // And yet you return the new array
    return reversed;
};

Array has a built-in method to reverse itself: Array#reverse(). It does exactly what you want: reverse the array in-place.

function reverseArrayOfStrings(s) {
  s.reverse();
};

Try it:

<!-- begin snippet: js hide: true -->

<!-- language: lang-js -->

console.config({ maximize: true });

function reverseArrayOfStrings(s) {
  s.reverse();
};

const testcase = [&#39;1&#39;, &#39;2&#39;, &#39;3&#39;];
console.log(testcase);

reverseArrayOfStrings(testcase);
console.log(testcase);

<!-- language: lang-html -->

&lt;script src=&quot;https://gh-canon.github.io/stack-snippet-console/console.min.js&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

If you want to write your own, read on.

First, we make a middle point and call it pivot: pivot = Math.floor(s.length / 2). It serves as the stop for our loop. Then, we swap the elements, pair by pair:

Original:
┌───────────┬─────┬─────┬─────┬─────┬─────┐
│ Indices:  │  0  │  1  │  2  │  3  │  4  │
├───────────┼─────┼─────┼─────┼─────┼─────┤
│ Elements: │ &#39;1&#39; │ &#39;2&#39; │ &#39;3&#39; │ &#39;4&#39; │ &#39;5&#39; │
└───────────┴─────┴─────┴─────┴─────┴─────┘

Swap the element at index 0 with the one at 4:
┌───────────┬─────┬─────┬─────┬─────┬─────┐
│ Indices:  │  0  │  1  │  2  │  3  │  4  │
├───────────┼─────┼─────┼─────┼─────┼─────┤
│ Elements: │ &#39;5&#39; │ &#39;2&#39; │ &#39;3&#39; │ &#39;4&#39; │ &#39;1&#39; │
└───────────┴─────┴─────┴─────┴─────┴─────┘

Swap the element at index 1 with the one at 3:
┌───────────┬─────┬─────┬─────┬─────┬─────┐
│ Indices:  │  0  │  1  │  2  │  3  │  4  │
├───────────┼─────┼─────┼─────┼─────┼─────┤
│ Elements: │ &#39;5&#39; │ &#39;4&#39; │ &#39;3&#39; │ &#39;2&#39; │ &#39;1&#39; │
└───────────┴─────┴─────┴─────┴─────┴─────┘

Swap the element at index 2 with itself (i.e. no change):
┌───────────┬─────┬─────┬─────┬─────┬─────┐
│ Indices:  │  0  │  1  │  2  │  3  │  4  │
├───────────┼─────┼─────┼─────┼─────┼─────┤
│ Elements: │ &#39;5&#39; │ &#39;4&#39; │ &#39;3&#39; │ &#39;2&#39; │ &#39;1&#39; │
└───────────┴─────┴─────┴─────┴─────┴─────┘

Let's call the indices to swap in one turn x and y (x &lt;= y). x starts at 0, whereas y starts at s.length - 1 (5 - 4). x increases by 1 each turn, whereas y decreases by 1 in the same turn. This leads to a formula:

y = s.length - x - 1

To make things easy, we loop from 0 to pivot, inclusively. This makes x the same as index:

for (let index = 0, pivot = Math.floor(s.length / 2); index &lt; pivot; index++) {
    // This syntax is called &quot;destructuring&quot;.
    // It assigns the current value of s
展开收缩
to s[index]
// and vice versa concurrently, effectively swapping their places. [s[index], s[s.length - index - 1]] = [s[s.length - index - 1], s[index]]; // To compare:
展开收缩
, s[y]] =
展开收缩
, s[x]];
}

Try it:

<!-- begin snippet: js hide: true console: false babel: false -->

<!-- language: lang-js -->

console.config({ maximize: true });

function reverseArrayOfStrings(s) {
  for (let index = 0, pivot = Math.floor(s.length / 2); index &lt; pivot; index++) {
      // This syntax is called &quot;destructuring&quot;
      // It assigns the current value of s
展开收缩
to s[index] // and vice versa concurrently, effectively swapping their places.
展开收缩
, s
展开收缩
] =
展开收缩
, s[index]]; } }; const testcases = [ [&#39;1&#39;, &#39;2&#39;, &#39;3&#39;], [&#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;] ]; testcases.forEach(testcase =&gt; { console.log(&#39;Original:&#39;, testcase); reverseArrayOfStrings(testcase); console.log(&#39;Modified:&#39;, testcase); });

<!-- language: lang-html -->

&lt;script src=&quot;https://gh-canon.github.io/stack-snippet-console/console.min.js&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

As a side note, a recent change to JS adds a method for creating a reversed array without modifying the original: Array#toReversed().

huangapple
  • 本文由 发表于 2023年6月6日 01:33:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76408781.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定