为什么剪接删除我的整个数组?我只想在位置0时删除它

发布于 2025-02-13 05:51:19 字数 795 浏览 0 评论 0原文

我正在处理以下说明的LEET代码问题:

您将获得一个阵列价格,其中价格[i]是当天给定股票的价格。

您希望通过选择一天购买一只股票并选择将来的不同一天来出售该股票来最大化利润。

从这笔交易中返回您可以实现的最大利润。如果您无法获得任何利润,请返回0。

在下面的我的代码中,我希望仅在数组的索引0中删除数组中的最大号码。检查调试器时,我看到整个数组被删除了索引0。为什么剪接不按预期工作?

调试器显示什么

var maxProfit = function (prices) {
  let theMin = Math.min(...prices)
  let minPosition = prices.indexOf(theMin)
  let theMax = Math.max(...prices)
  let maxPosition = prices.lastIndexOf(theMax)

  if (maxPosition === 0) {
    prices = prices.splice(0, 1)
    if (prices.length === 0) {
      return 0
    }

    maxProfit(prices)
  }

  return theMax - theMin
};

I'm working on a leet code problem with the following instructions:

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

In my code below, I expect to remove the Max number from the array only if it's in index 0 of the array. When checking the debugger, I see that the entire array is deleted except index 0. Why is splice not working as intended?

what debugger shows
leetcode debugger view showing the entire array deleted

var maxProfit = function (prices) {
  let theMin = Math.min(...prices)
  let minPosition = prices.indexOf(theMin)
  let theMax = Math.max(...prices)
  let maxPosition = prices.lastIndexOf(theMax)

  if (maxPosition === 0) {
    prices = prices.splice(0, 1)
    if (prices.length === 0) {
      return 0
    }

    maxProfit(prices)
  }

  return theMax - theMin
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

耳根太软 2025-02-20 05:51:19

剪接不返回数组的修改副本。阵列在现场修改,返回的是已删除的子阵列(如果有)。

实际上,您的代码是:

const deletedElements = prices.splice(0, 1);
prices = deletedElements;

您从数组中删除第一个元素,然后用仅包含第一个元素的另一个数组代替该数组。因此,正如您声称的那样,不仅仅是返回第一个元素。 剪接正常工作。


另外,price.splice(0,1)更明确地写成prices.shift()

splice does not return a modified copy of the array. The array is modified in-place, and what is returned is the deleted subarray, if any.

In effect, your code is:

const deletedElements = prices.splice(0, 1);
prices = deletedElements;

You deleted the first element from the array, then replaced that array with another array which only contains the first element. Thus, it is not that only the first element is returned, as you claim. splice is working exactly as documented.


Also, prices.splice(0, 1) is more legibly written as prices.shift().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文