【问题标题】:Find the least number of jumps required to get from one number to another [closed]找到从一个数字到另一个数字所需的最少跳跃次数[关闭]
【发布时间】:2020-04-21 04:41:36
【问题描述】:

我有一个想用 javascript 解决的问题。任何帮助如何解决这个问题?下面是问题。 使用下面的数组元组找到从 1 到 15 所需的最少跳转次数。例如,从 1 到 4 需要 2 次跳跃 - [1,3] 后跟 [3,4]。

var x = [[1,2], [1,3], [3,4], [4,5], [5,6], [5,7],
  [1,7], [2,8], [8,9], [9,11], [9,10], [7,10],
  [10,12], [10,14], [12,13], [14,15]]```

【问题讨论】:

  • @CertainPerformance 这是一个我无法解决的问题,这就是我在这里问的原因。 :(
  • x 是动态的吗? x中的跳跃值会改变吗?它是否总是以索引 0 处为 1 的数组开始,最终以索引 1 处为 15 的数组结束?

标签: javascript jquery ecmascript-6


【解决方案1】:

这是一个 dp 解决方案。请查看我在代码 sn-p 中的评论以获取解释。需要 O(target) 空间来保存 dp 数组。 O(nlogn) 时间复杂度,其中 n 是数据数组的长度。

const data = [[1,2], [1,3], [3,4], [4,5], [5,6], [5,7],
  [1,7], [2,8], [8,9], [9,11], [9,10], [7,10],
  [10,12], [10,14], [12,13], [14,15]];
  
  
const minJump = (target) => {
  //dp array to memorize min jump need at each position
  const dp = new Array(target+1);
  dp[1] = 0;
  //sort data array by start point
  data.sort((a,b) => a[0]-b[0]);
  for(const [start, end] of data){
    //if start position has never been reached before, it's an invliad jump
    if(dp[start] === undefined) continue;
    //compare min jump needs at end position, if it's undefined, we haven't reached end position before
    dp[end] = dp[end] === undefined ? dp[start] + 1 : Math.min(dp[start] + 1, dp[end])
  }
  
  //return -1 if dp[target] is undefined which means we can't reach at the target position
  return dp[target] || -1
}

console.log(minJump(15))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 2014-05-18
    • 2013-08-14
    • 2010-12-07
    • 2019-03-19
    相关资源
    最近更新 更多