gpt4 book ai didi

javascript - 缺少整数代码Javascript

转载 作者:行者123 更新时间:2023-12-03 16:30:28 26 4
gpt4 key购买 nike

Write a function:

function solution(A); 

that, given a non-empty zero-indexed array A of N integers, returns the minimal positive integer (greater than 0) that does not occur in A. For example, given:

A[0] = 1   
A[1] = 3
A[2] = 6
A[3] = 4
A[4] = 1
A[5] = 2

the function should return 5. Assume that:

• N is an integer within the range [1..100,000]; • each element of array A is an integer within the range

[−2,147,483,648..2,147,483,647].

Complexity: • expected worst-case time complexity is O(N); • expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).



我的答案是 100% 错误的!它有什么问题?首先让我说明明显的错误
  • 返回值 - 我返回 0,因为如果没有丢失整数,则没有指示返回什么。

  • 我所做的假设可能是错误的
  • 返回 A 中不出现的最小正整数(大于 0)。这里我不检查负值

  • 我的代码适用于自己的测试用例,也适用于负数,得到 0%。
    function solution(A) {

    // write your code in JavaScript (Node.js 0.12)
    A.sort();
    var a_length = A.length;

    for(var i = 0; i < a_length; i++){

    // if i is 0 - 1 = -1 then do not do the following
    // if i is 1 - 1 - 0 then do the follow
    // if i >= 0 then do the following
    if(i - 1 >= 0){

    // remember above there is a A.sort() so it
    // looks like this
    // A[0] = 1
    // A[1] = 1
    // A[2] = 2
    // A[3] = 3
    // A[4] = 4
    // A[5] = 6

    // if A[1] is 1 and A[1-1 = 0] is 1 then this is 1>1 false
    // if A[2] is 2 and A[2-1 = 1] is 1 then this is 1>1 false
    // if A[3] is 3 and A[3-1 = 2] is 2 then this is 1>1 false
    // if A[4] is 4 and A[4-1 = 3] is 3 then this is 1>1 false
    // if A[5] is 6 and A[5-1 = 4] is 4 then this is 2>1 true return A[i - 1] + 1 where A[5 - 1 = 4] is 4 + 1 is 5. 5 is returned.
    if(A[i] - A[i - 1] > 1){
    return A[i - 1] + 1;
    }
    }
    }

    // this does not check for negative
    // returns the minimal positive integer (greater than 0
    // this is a return no minimal positive integer found
    return 0;
    }

    一切都错了,示例测试结果:

    简单的简单测试
    0.072 秒
    错误的答案
    得到 3 预期 1

    为什么它对我有用,而不对他们有用。

    最佳答案

    function solution(A) {
    var min = 1;
    A.sort(function(a,b){
    // Sort the array explicit way
    return a - b;
    });

    for (var i in A) {
    if (A[i] > -1 && A[i] == min) {
    min++;
    }
    }

    return min;
    }

    关于javascript - 缺少整数代码Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30724992/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com