【问题标题】:How to find i and j indeces of an array where A[j] - A[i] is the maximum value and i < j?如何找到 A[j] - A[i] 是最大值且 i < j 的数组的 i 和 j 索引?
【发布时间】:2021-10-03 13:43:40
【问题描述】:

我已经为这个问题找到了很多解决方案,但时间复杂度却是 O(n^2)。我试图找到时间复杂度为 O(n) 的解决方案。 我在那里看到的解决方案:https://www.geeksforgeeks.org/maximum-difference-between-two-elements/ 工作正常,但是如何获得数字而不使其更复杂? 感谢您的回答!

【问题讨论】:

  • 如果你能在 O(n) 中找到数字,你也可以在 O(n) 中找到它们的索引,只需在之后搜索它们。但是调整代码以跟踪索引应该不是那么难。

标签: algorithm max


【解决方案1】:

我相信这行得通:

  • 迭代数组,跟踪索引到目前为止的最小值 (O(n))
    • 为每个索引在映射中插入一个条目:索引 -> currMinIdx
    • 如有必要,使用当前值更新 currMinIdx
  • 您现在拥有与每个索引关联的最小值索引的映射
  • 迭代该映射并确定最大差异 (O(n))

在伪代码中:

//init variables
int currMinIdx = -1
map<Int, Int> maxIdxToMinIdxMap // a map of the index of the min value for a given index

//iterate the array to populate the map
for every i in A:    
    maxToMinIdxMap[i] = currMinIdx
    if A[i] < A[currMinIdx]:
        currMinIdx = i


int currMinIdx2 = -1
int currMaxIdx2 = -1
int currMaxDiff

for every entry in maxIdxToMinIdxMap:
     if A[entry.key] - A[entry.value] > currMaxDiff:
          currMaxDiff = A[entry.key] - A[entry.value]
          currMaxIdx2 = entry.key
          currMinIdx2 = entry.value

【讨论】:

  • 现在看你贴的链接,我相信这对应方法二。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
  • 2017-09-10
  • 2019-04-19
  • 2012-10-20
  • 2013-08-19
  • 2023-04-05
  • 2021-11-01
相关资源
最近更新 更多