Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用两个指针的算法的时间复杂度。是0(n)还是0(n^2)_Javascript_Algorithm_Time Complexity_Big O - Fatal编程技术网

Javascript 使用两个指针的算法的时间复杂度。是0(n)还是0(n^2)

Javascript 使用两个指针的算法的时间复杂度。是0(n)还是0(n^2),javascript,algorithm,time-complexity,big-o,Javascript,Algorithm,Time Complexity,Big O,这就是问题所在 给定一个整数数组,返回一个新数组,其中新数组中的每个元素都是原始输入数组中该元素右侧较小元素的数目 例如,给定数组[3,4,9,6,1],返回[1,1,2,1,0],因为: There is 1 smaller element to the right of 3 There is 1 smaller element to the right of 4 There are 2 smaller elements to the right of 9 There is 1 smaller

这就是问题所在

给定一个整数数组,返回一个新数组,其中新数组中的每个元素都是原始输入数组中该元素右侧较小元素的数目

例如,给定数组[3,4,9,6,1],返回[1,1,2,1,0],因为:

There is 1 smaller element to the right of 3
There is 1 smaller element to the right of 4
There are 2 smaller elements to the right of 9
There is 1 smaller element to the right of 6
There are no smaller elements to the right of 1
我想出了这个双指针算法

 function lessThan(arr) {
  let results = [];
  let i = 0;
  let j = arr.length - 1;
  let count = 0;
  while (i < arr.length) {
    if (arr[i] > arr[j]) {
      count++;
    }
    j--;
    if (j === 1) {
      results.push(count);
      count = 0;
      i++;
      j = arr.length - 1;
    }
  }
  return results;
}
功能缺失(arr){
让结果=[];
设i=0;
设j=arr.length-1;
让计数=0;
而(iarr[j]){
计数++;
}
j--;
如果(j==1){
结果:推(计数);
计数=0;
i++;
j=阵列长度-1;
}
}
返回结果;
}
指针“i”将从开头开始,“j”将从结尾开始。 如果“j”等于1,“i”将递增,“j”将重置为结尾。 这一直持续到“i”到达数组的末尾。(当“i”等于或大于arr.length时,while循环中断)。 根据我对时间复杂度的了解,我猜当我们遍历数组时,它只有一次是O(n)。 但是,我们不应该考虑这样一个事实,即在我们经过时,对“j”进行了“n”比较吗? 我不熟悉竞争性编程和大O符号。请帮助我

谢谢。

它是O(n²),你每
len(arr)
迭代一次,就增加
i
直到
i
达到
len(arr)


这给了
len(arr)*len(arr)
的复杂性,即O(n²)。

您可以将代码重新排列为

 function lessThan(arr) {
  let results = [];
  let i = 0;
  while (i < arr.length) {
    let j = arr.length - 1;
    let count = 0;
    while (j !== 1) {
      if (arr[i] > arr[j]) {
        count++;
      }
      j--;
    }
    results.push(count);
    i++;
  }
  return results;
}
功能缺失(arr){
让结果=[];
设i=0;
而(iarr[j]){
计数++;
}
j--;
}
结果:推(计数);
i++;
}
返回结果;
}
是的,您已经巧妙地将嵌套循环合并为单个循环,但这并没有改变其复杂性。请注意,在您的版本中,
while
循环运行
arr.length²
次,因为
i
不会在每次迭代中递增,而仅在
j==1
时递增


从我的更新版本中,不仅可以清楚地看到代码是
O(n²)
,而且它是错误的:
j!==1
(或
j>1
)应该与
i
相比较,而不是
1
-你只想计算右边的元素。

我不知道你怎么能以一种不是最终O(n^2)的方式来做这件事。@Pointy我很确定你可以在
O(n log n)中做
如果您保留一个排序数组并从右向左遍历输入。不,您不能@Bergi。如果您对它进行排序。对于9,将有4个元素小于它。但是如果您阅读问题描述。如果您考虑一个值范围非常广的非常大的数组,这将导致错误答案,似乎一系列的迭代是不可避免的。可能有一种“动态规划”方法(如果这个术语在我学了40年后仍在使用的话)会起作用,但我永远也搞不清楚。