Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/441.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.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 可变性-最小平均切片_Javascript_Algorithm_Dynamic Programming_Kadanes Algorithm - Fatal编程技术网

Javascript 可变性-最小平均切片

Javascript 可变性-最小平均切片,javascript,algorithm,dynamic-programming,kadanes-algorithm,Javascript,Algorithm,Dynamic Programming,Kadanes Algorithm,我试图找到一个解决方案,我已经设计了一个使用卡丹算法的改进版本的解决方案。我目前的成绩是90/100,并且几乎通过了O(n)中的所有测试。然而,我似乎不能通过“中等范围,递增,递减(legth=~100)和小函数,得到5个期望值3”,我不知道为什么。这可能是重复的,但我使用了一种稍微不同的解决方法 我的逻辑如下: a) 如果我们有一个数组MinA,其中MinA[k]表示从k开始的子数组的最小平均切片,最小长度为2 b) 然后,如果我们通过MinA循环并找到数组的最小值,那么这将是整个数组的最小平

我试图找到一个解决方案,我已经设计了一个使用卡丹算法的改进版本的解决方案。我目前的成绩是90/100,并且几乎通过了O(n)中的所有测试。然而,我似乎不能通过“中等范围,递增,递减(legth=~100)和小函数,得到5个期望值3”,我不知道为什么。这可能是重复的,但我使用了一种稍微不同的解决方法

我的逻辑如下:

a) 如果我们有一个数组MinA,其中MinA[k]表示从k开始的子数组的最小平均切片,最小长度为2

b) 然后,如果我们通过MinA循环并找到数组的最小值,那么这将是整个数组的最小平均切片(然后返回索引位置)

c) 为了创建这个MinA,我们从数组的第二个最后元素开始,MinA[A.length-2]是数组最后两个元素的平均值

d) 我们将计数器向左移动一个位置;MinA[counter]必须是[counter]和[counter+1]的平均值,或者是元素计数器和MinA[counter+1]中元素的平均值

e) 如果d不是真的,那么这意味着MinA[counter+1]不是从计数器+1到计数器+2到N的某个元素的最小平均切片

我想知道我是否遗漏了什么

/*
 * Using modified version of Kadane's algorithm
 * The key logic is that for an array A of length N, 
 * if M[k + 1] is the minimum slice of a subarray from k + 1 to any element
 * between k+2 to n, then M[k] is either the average of A[k] and A[k + 1], or
 * the average of the elements k and the elements in M[k + 1]
 */
function solution(A) {
    // you can use console.log for debugging purposes, i.e.
    // console.log('this is debug message');
    // write your code in JavaScript (ECMA-262, 5th edition)
    var minSliceArray = [],
        counter = A.length - 2,
        currMinSliceLength = 0,
        min = Number.POSITIVE_INFINITY,
        minIndex = -1;

    minSliceArray[counter] = (A[counter] + A[counter + 1]) / 2;
    currMinSliceLength = 2;
    counter--;

    while (counter >= 0) {
        var a = (A[counter] + A[counter + 1]) / 2,
            b = (A[counter] + minSliceArray[counter + 1] * currMinSliceLength) / (currMinSliceLength + 1) ;
        if (a < b) {
            minSliceArray[counter] = a;
            currMinSliceLength = 2;
        } else {
            minSliceArray[counter] = b;
            currMinSliceLength++;
        }
        counter--;
    }

    //loops through the minSliceArray and find the minimum slice
    for (var i = 0; i < minSliceArray.length; i++) {
        if (minSliceArray[i] < min) {
            min = minSliceArray[i];
            minIndex = i;
        }
    }
    return minIndex;
}
/*
*使用Kadane算法的改进版本
*关键逻辑是,对于长度为N的数组,
*如果M[k+1]是从k+1到任意元素的子阵列的最小切片
*在k+2到n之间,那么M[k]是A[k]和A[k+1]的平均值,或者
*元素k和元素M[k+1]的平均值
*/
函数解(A){
//您可以使用console.log进行调试,即。
//log('这是调试消息');
//用JavaScript编写代码(ECMA-262,第5版)
var minSliceArray=[],
计数器=A.长度-2,
currMinSliceLength=0,
最小值=正无穷大,
minIndex=-1;
minSliceArray[counter]=(A[counter]+A[counter+1])/2;
电流长度=2;
计数器--;
而(计数器>=0){
变量a=(a[计数器]+a[计数器+1])/2,
b=(A[计数器]+minSliceArray[计数器+1]*currMinSliceLength)/(currMinSliceLength+1);
if(a
怎么样

Javascript

function solution(A) {
    var minpos = 0,
        minavg = (A[0] + A[1]) / 2,
        N = A.length,
        N1 = N - 1,
        N2 = N - 2,
        sumTwo,
        t,
        i;

    for (i = 0; i < N2; i += 1) {
        sumTwo = A[i] + A[i + 1];
        t = sumTwo / 2;
        if (minavg > t) {
            minavg = t;
            minpos = i;
        }

        t = (sumTwo + A[i + 2]) / 3;
        if (minavg > t) {
            minavg = t;
            minpos = i;
        }

    }

    t = (A[N2] + A[N1]) / 2;
    if (minavg > t) {
        minavg = t;
        minpos = N2;
    }

    return minpos;
}

var A = [4, 2, 2, 5, 1, 5, 8];

console.log(solution(A));
函数解决方案(A){
var minpos=0,
minavg=(A[0]+A[1])/2,
N=A.长度,
N1=N-1,
N2=N-2,
二,,
T
我
对于(i=0;it){
minavg=t;
minpos=i;
}
t=(sumtoo+A[i+2])/3;
如果(minavg>t){
minavg=t;
minpos=i;
}
}
t=(A[N2]+A[N1])/2;
如果(minavg>t){
minavg=t;
minpos=N2;
}
返回minpos;
}
VarA=[4,2,2,5,1,5,8];
console.log(解决方案(A));

上,要解决问题,可以替换代码

if (a < b) {
if(a


if(a虽然Sheng的修正确实有帮助,但该算法仍然不能在所有情况下都有效。
例如,对于
[-18、65、-11、73、-22、90、21、10、47、87]
,算法返回
2
。预期值为
0

可能原因: 考虑算法的中间步骤。如果A[i..j]具有从i开始的切片的最小平均值,则要包括i-1处的元素,仅考虑以下选项:

  • A[i-1…j]
  • A[i-1…i]
不幸的是,可能存在一个索引
k
,使得
avg(A[i…k])>avg(A[i…j])
,但是
avg(A[i-1…k])
。虽然这可以从数学上证明,但这里只有一个例子就足够了

[-18,65,11,73,22,90,21,10,47,87]
平均值([65,-11,73,-22])=26.25
平均值([65,-11])=27//由于平均值较高,因此忽略该值

为了包含-18,该算法考虑了
[-18,65,-11,73,-22]
[-18,65]

avg([-18,65,-11,73,-22])=17.4
平均值([-18,65])=23.5
平均值([-18,65,-11])=12//未考虑的真实最小值

我提交了一个类似的解决方案,它的代码性得分为100%。但是,它不是正确的解决方案。

在此基础上,我有一个O(2NN)算法,它很简单,但只有40%的正确性和0%的性能:

function solution(A) {
    var m = null, c, n
    for ( var i = 0; i < A.length; ++i ) {
        for ( var j = i + 1; j <= A.length; ++j ) {
            c = A.slice(i, j + 1).reduce(function (a,b) { return a+b }) / (j - i + 1)
            if ( m === null || c < m ) {
                m = c
                n = i
            }
            else if ( c == m && i < n ) {
                n = i
            }
        }
    }
    return n
}
function solution(A) {
    if ( A.length < 2 )  return -1
    var result = A.reduce(function (a, b, bIndex) {
        var f = typeof a === 'number'
        var x, y, z
        z = {
            index: bIndex,
            value: b,
            couple: {
                start: bIndex - 1,
                sum:   x = (f ? a : a.value) + b,
                count: 2,
                avg:   x / 2
            },
            streak: {
                start: a.bestStreak ? a.bestStreak.start : 0,
                sum:   x = (f ? a : a.bestStreak.sum) + b,
                count: y = (f ? 1 : a.bestStreak.count) + 1,
                avg:   x / y
            }
        }

        z.bestStreak = z.couple.avg < z.streak.avg
            ? z.couple
            : z.streak

        z.best = !a.best || z.bestStreak.avg < a.best.avg
            ? z.bestStreak
            : a.best

        // console.log(JSON.stringify({z}, null, '  '))

        return z
    })
    return result.best.start
}
函数解决方案(A){
var m=null,c,n
对于(变量i=0;i对于(var j=i+1;j,在另一篇文章中,我提供了我的详细描述。我不在这里包括它,因为你已经有了这个想法

int solution(vector<int> &A) {

    // Find prefix sum.
    int N = A.size();
    vector<int> ps(N + 1, 0);

    for (int i = 1; i <= N; i++) {
        ps[i] = A[i - 1] + ps[i - 1];
    }

    int lft_idx, min_lft_idx;
    double avg_here, min_avg, avg_of_two, avg_with_prev;

    // Initialize variables at the first possible slice (A[0:1]).
    lft_idx = min_lft_idx = 0;
    avg_here = min_avg = (A[0] + A[1]) / 2.0;

    // Find min average of every slice that ends at ith element,
    // starting at i = 2.
    for (int i = 2; i < N; i ++) {

        // average of A[lft_idx : i]
        avg_with_prev = ((double) ps[i + 1] - ps[lft_idx]) / 
                        (i - lft_idx + 1);

        // average of A[i - 1 : i]
        avg_of_two = (A[i - 1] + A[i]) / 2.0;

        // Find minimum and update lft_idx of slice
        // (previous lft_idx or i - 1).
        if (avg_of_two < avg_with_prev) {
            avg_here = avg_of_two;
            lft_idx = i - 1;
        }
        else
            avg_here = avg_with_prev;

        // Keep track of minimum so far and its left index.
        if (avg_here < min_avg) {
            min_avg = avg_here;
            min_lft_idx = lft_idx;
        }
    }

    return min_lft_idx;
}
int解决方案(向量&A){
//查找前缀和。
int N=A.size();
向量ps(N+1,0);

对于(int i=1;i Hmmm,它说它是N^2复杂性()对不起,孩子们也都是流感。我严重误读和过度复杂的东西。这更好吗,还是我仍然误解了这个问题?对不起,如果我刚才真的很笨的话。:)非常感谢,这很有意义!
int solution(vector<int> &A) {

    // Find prefix sum.
    int N = A.size();
    vector<int> ps(N + 1, 0);

    for (int i = 1; i <= N; i++) {
        ps[i] = A[i - 1] + ps[i - 1];
    }

    int lft_idx, min_lft_idx;
    double avg_here, min_avg, avg_of_two, avg_with_prev;

    // Initialize variables at the first possible slice (A[0:1]).
    lft_idx = min_lft_idx = 0;
    avg_here = min_avg = (A[0] + A[1]) / 2.0;

    // Find min average of every slice that ends at ith element,
    // starting at i = 2.
    for (int i = 2; i < N; i ++) {

        // average of A[lft_idx : i]
        avg_with_prev = ((double) ps[i + 1] - ps[lft_idx]) / 
                        (i - lft_idx + 1);

        // average of A[i - 1 : i]
        avg_of_two = (A[i - 1] + A[i]) / 2.0;

        // Find minimum and update lft_idx of slice
        // (previous lft_idx or i - 1).
        if (avg_of_two < avg_with_prev) {
            avg_here = avg_of_two;
            lft_idx = i - 1;
        }
        else
            avg_here = avg_with_prev;

        // Keep track of minimum so far and its left index.
        if (avg_here < min_avg) {
            min_avg = avg_here;
            min_lft_idx = lft_idx;
        }
    }

    return min_lft_idx;
}