missinginteger codility Javascript

时间:2015-06-09 06:57:23

标签: javascript

  

写一个函数:

function solution(A); 
     

给定N个整数的非空零索引数组A,返回最小的正整数(大于0)   在A中出现。例如,给定:

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

该函数应返回5.假设:

• 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]。

     

复杂度:       •预期的最坏情况时间复杂度为O(N); •预期的最坏情况空间复杂度为O(N),超出输入存储(不是   计算输入参数所需的存储空间。)

我的回答是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

为什么它适用于我而不适合他们。

30 个答案:

答案 0 :(得分:12)

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;
}

答案 1 :(得分:5)

我的解决方案是使用JavaScript for Codility MissingInteger(得到100/100)

id

答案 2 :(得分:3)

function solution(A) {
        A.sort(function(a,b){
           // Sort the array explicit way
           return a - b; 
        });
        return A.reduce((prev, next)=> {
            if(next > -1 && next === prev) {
                prev++;
            }
            return prev;
        }, 1);
     ;
}

答案 3 :(得分:2)

function solution(A) {
// write your code in JavaScript (Node.js 6.4.0)
var b = A.sort(function(a,b){return a-b});
var length = b.length;
var min = b[0];
var max = b[length-1];
if (max<=0){return 1;}
if (min<=0 && max==1){return 2;}
if (min>1){return 1;}
if (min >=0){
    for(var i=0; i<length; i++){
       if(b[i+1]- b[i] > 1){
           return b[i]+1;
       }
    }
}
if (min<=0 && max>=0){
    for(var i=0; i<length; i++){
        if(b[i]>0 && b[i-1]<=0){
            if(b[i]-0>1){
               return 1; 
            }
            if(b[i+1]-b[i]>1){
                return b[i]+1;
            }
        }
        if(b[i]>0){
            if(b[i+1]- b[i] > 1){
               return b[i]+1;
            }
        }
    }
}
return max+1;

}

答案 4 :(得分:1)

我的最终解决方案:

function solution(A) {
    A = [...new Set(A)];
    let min = 1;
    A.sort((x,y) => x-y);
    for (i in A) {
       if (A[i] > -1 && A[i] == min) { min ++;}
    }
return min;
}

我发现删除数组中的重复项很重要,然后在为解决方案提供资金时以这种方式对其进行分类。

test:solution([1,2,5,7,8,3,4,2,1,9,3,3,3,3,3,3,3,3,3,3,3,3, 3,33,3,3,3,36,-2,-1,-1,6,10,12,13,13,13,13,15,14,17,10])->结果11; < / p>

Result

答案 5 :(得分:1)

满分100分:

function solution(A) {
    // write your code in JavaScript (Node.js 8.9.4)
    const B = Array.from(new Set(A)).filter(v => v > 0).sort((a,b) => a - b);
    //First create a unique Array by creating a new set, 
    //which then we filter on values greater than 0. 
    //We sort with an explicit function, 
    //otherwise our integers are converted to strings 
    //and sorting will be based on first character rather than on value

    let i = 1; //set our initial value

    for(const val of B){ //iterate over the unique values
        if(i < val){
            return i; 
            //if val is greater than i, that means the value of i was
            //not present in our  array hence we return it
        }
        i++; //if the value was present we go to the next value, hence increase by 1
    }
    return i; 
    //if we went over the whole array, that means all values were present;
    //hence the new value of i, which equals to the highest value of the array + 1 is the correct answer.
    //Since the loop would not run in case of an empty array (which due to the filter also occurs in case of negative values), 
    //the value of i is still 1 and the correct answer.
}

如果您不想使用set(例如,因为您使用的是旧版ES),则可以按以下方式进行过滤:

A.filter((v,i,arr) => v > 0 && arr.indexOf(v) === i)

答案 6 :(得分:0)

尝试这样的事情:

// Array containing your numbers
var Arr = [1, 3, 6, 4, 1, 2];
solution(Arr);

function solution(Arr) {
    var len = Arr.length;
    var min = 100001;
    var num;

    // check if it is empty
    if (len == 0) {
        alert('Empty zero-indexed array given');
    }

    // find array's min number
    for(var i = 0; i < len; i++) {
        if (Arr[i] < min) {
            min = Arr[i];
        }
    }

    for (var i = 0; i < 100000; i++) {
        var x = Arr.indexOf(min);
        if (x == -1) {
            num = min;
            break;
        }
        min++;
    }

    alert('Min value in array is: ' + num);
}

这是一个有效的Jsfiddle demo

答案 7 :(得分:0)

  • 首先获取数组的最大数量。
  • 然后将 1 迭代到最大数字并检查数组中不存在的数字并返回该数字。
  • 否则返回 max+1;
function solution(A) 
    {    
        var max = A.reduce(function(a, b) {
            return Math.max(a, b);
        });    
        for(var i = 1; i <= max; i++){
            if(!A.includes(i)){
                return i;
            }
        }
        if(i > max){
            return i;
        }
    }

答案 8 :(得分:0)

function solution(A) {
    const dict = {};
    let startFrom = 1;
    for (let item of A) {
        dict[item] = true;            
        // keep startFrom greater than every number already in the dictionary
        while(dict[startFrom]) {
            startFrom++;
        }
    }
    return startFrom;
}

答案 9 :(得分:0)

function solution(A) {
  // write your code in JavaScript (Node.js 8.9.4)
  const set = new Set();
  const N = A.length;
  let max = 0;

  A.forEach((ele) => {
    if (ele > 0) {

      set.add(ele);

      if (ele > max) {
        max = ele;
      }
    }
  });

  for (let i = 1; i < N + 1; i++) {
    if (!set.has(i)) {
      return i;
    }
  }

  return max + 1;
}

答案 10 :(得分:0)

对于JavaScript,请尝试以下操作。考试分数100/100

检测到的时间复杂度:O(N)或O(N * log(N))

function solution(A) {
     var missingInt = 1;

    A.sort((a, b) => { return a - b; });

    for (var i = 0; i < A.length; i++) {
        if (A[i] >= (missingInt + 1)) {
            break;
        }
        if (A[i] == missingInt) {
            missingInt++;
        }

    }

    return missingInt++;
}

答案 11 :(得分:0)

尝试以下操作,

let expecterNumber = 1;
        A.sort(function(a,b){
           return a - b; 
        });

        for (let i in A) {
            if (A[i] <= 0 || A[i] == A[i - 1]) continue 
            if (A[i] != expecterNumber) break

            expecterNumber++;
        }

        return expecterNumber;
}

答案 12 :(得分:0)

下面的代码是用JS编写的

function solution(A) {

//Removing duplicate elements by using Set
A = Array.from(new Set(A));

// Sorting the array in ascending order
A.sort((a,b) => a-b);

let arrayLength = A.length;

// All negative numbers,if any, will be located in the beginning of the array after sorting, Hence removing them without iterating entire array (saves time complexity).

if(arrayLength) {   // Check for empty array
let removedItem = A.shift();
while(removedItem <= 0) {
    removedItem = A.shift();
    arrayLength--
}
A.unshift(removedItem); // last Element removed will either be negative(if all elements in array are negative) or a positive number. Hence pushing it back in to array.
}

// If first element is not 1 simply return 1, bcz that's the 1st  misssing integer.
if(A[0] != 1)
 return 1;

// Finding the first missing integer - Worst Case Complexity - O(n).
let missingInteger = -1;
let i=0;
while(missingInteger < 0 && i <= arrayLength) {
    if(A[i]+1 != A[i+1])
      missingInteger = A[i]+1;
    i++;
}
return missingInteger < 0? A[arrayLength - 1] + 1 : missingInteger;
}

希望有帮助。

答案 13 :(得分:0)

这里有好几个回应。最简洁,最优雅的IMO是@ben_flock的https://stackoverflow.com/a/54079690

但是,只想演示一个稍微更“有效”的选项。即,排序后不必遍历整个数组。它会尽快短路。

K-means

在此答案中,我使用了Array.prototype.sort()Array.prototype.some()ternary

答案 14 :(得分:0)

function solution(A) {
var swap = function(i, j) {
    var tmp = A[i];
    A[i] = A[j];
    A[j] = tmp;
};
for (let i = 0; i < A.length; i++) {
    while (0 < A[i] && A[i] - 1 < A.length
            && A[i] != i + 1
            && A[i] != A[A[i] - 1]) {
        swap(i,A[i] - 1);
    }
}
for (let i = 0; i < A.length; i++) {
      if (A[i] != i + 1) {
         return i + 1;
      }
   }
return A.length + 1;
}

这是您要寻找的最终解决方案

答案 15 :(得分:0)

这是我在测试过程中尝试的解决方案。并非经过优化,但足够易于阅读。

想法:

  • 创建一个从1开始的循环,因为我们只在寻找正整数
  • 对于每次迭代,请检查数组中是否有当前数字。
  • 如果不可用,请中断循环。

function solution(arr) {
  let i;
  let num = 1;
  for (i = 1; i <= arr.length; i++) {
    let exists = arr.some((n) => n === i);
    if (!exists) {
      num = i;
      break;
    }
  }
  return num;
}

console.log(solution([2, 3, 4, 5, 5]))

console.log(solution([2, 3, 4, 5, 5, 1]))


使用哈希图的解决方案2:

这是一种性能更高,更建议的解决方案。

  • 遍历数组并创建值的哈希图。这将删除重复项,并使查找变得容易。
  • 还创建一个变量max并计算数组中的最大值。
  • 现在循环从1到最大。
    • 如果找不到值,则返回索引。
    • 如果所有值都存在,则返回max + 1

function solution(arr) {
  let max = 0;
  const hashMap = arr.reduce((map, num) => {
    map[num] = true;
    max = max > num ? max : num;
    return map
  }, {});
  
  for(let i = 1; i <= max; i++) {
    if (!hashMap[i]) return i
  }
  return max + 1;
}

console.log(solution([2, 3, 4, 5, 5]))

console.log(solution([2, 3, 4, 5, 5, 1]))

答案 16 :(得分:0)

任务得分:100% 正确性:100% 效果:100%

function solution(A) {
    // write your code in JavaScript (Node.js 8.9.4)

    let map = {};
    A.map(x => { map[x] = x; return x });

    let result = 1;
    while (true) {
        if (!map[result]) return result;
        result++;
    };
}

答案 17 :(得分:0)

notifyDataSetChanged

答案 18 :(得分:0)

我的JS解决方案获得了100分。基本上,我会生成一个新数组,其键将是原始数组的值,并将每个值设置为真实值。这有两件事:将负值带出新数组的迭代循环,还允许您从最小值开始循环并返回给您未定义的第一个索引。

function solution(A) {
    orderedArr = [];
    for (let i = 0; i < A.length; i++) {
        if (!orderedArr[A[i]]) {
            orderedArr[A[i]] = true;
         }
    }
    if (orderedArr.length === 0) return 1;
    for (let i = 1; i < orderedArr.length; i++) {
        if (!orderedArr[i]) {
            return i;
        }
    }
    return orderedArr.length;
}

答案 19 :(得分:0)

使用Javascript,我以一种奇怪的方式进行了此操作,但是我在任务得分,正确性和性能方面获得了100%的回报。但是,我得到了O(N)或O(N * log(N))。所以,我想降低它。

function solution(A){
    // remove all negative and zero 
    let positiveArray = A.filter(x => x > 0);
    // sort all positive values
    let sortedArray = positiveArray.sort((x,y) => x-y);
    // return first that doesn't appear in order
    return sortedArray.reduce((prev, next) => {
        if(next === prev){
            prev++
        }
        return prev;
    },1);
}

答案 20 :(得分:0)

这是我的解决方案,任务得分为66%,正确性为100%,性能仅为25%。不是性能最高的解决方案,而是有效的解决方案。

  1. 首先检查以确保数组中的最大数字大于0,否则,我们以1结束结果。
  2. 循环遍历从1到数组中最高的数字
  3. 如果该数字在数组中没有索引,那就是我们的结果
  4. 如果存在从1到数组中最高数字的所有数字,则结果为第二高数字
const test1 = [1, 3, 6, 4, 1, 2]; // Returns 5
const test2 = [1, 2, 3]; // Returns 4
const test3 = [-1, -3]; // Returns 1

function solution(A) {
  const lowestNum = Math.min.apply(Math, A);
  const highestNum = Math.max.apply(Math, A);

  // Check highestNum to make sure it's over 0
  if (highestNum > 0) {
    // Loop through all the numbers from 1 to the highes in the array
    for (var i = 1; i < highestNum; i++) {
      // If i does not have an index in the array, that's our solution
      if (Number(A.indexOf(i)) === -1) {
        return i;
      }
    }
    // If looped through array and all have an index, the next number is our answer
    return i + 1;
  } else {
  // If highestNum is not over 0, answer is 1
    return 1;
  }
}

solution(test1);

JS Fiddle demo

答案 21 :(得分:0)

对于这个问题,我想从给定数组排序开始。然后,我用reduce遍历排序后的数组。我给reduce一个累加器acc,最初等于1(这是逗号后的1)。仅当元素val等于累加器时,我才累加累加器。否则,我将原样返回累加器。当我再也找不到数组中等于累加器的元素时,该累加器就是丢失的最小正整数。

const solution = A => {
    A.sort((a, b) => a - b);
    return A.reduce((acc, val) => acc === val ? acc + 1 : acc, 1);
}

我知道这个问题已经存在了一段时间,但我希望这个答案对某人有用。在此答案中,我使用了Array.prototype.sort()Array.prototype.reduce()ternary。对这些模式的了解应该使人们对该答案有更多的了解。

答案 22 :(得分:0)

My swift 3 solution(100/100)

public func solution(_ A : inout [Int]) -> Int {
  let set = Set(A)
  var value = 1
  while true {
    if !set.contains(value) {
      return value
    }
    value += 1
  }
}

答案 23 :(得分:0)

我试图实现类似于Java中使用的JavaScript解决方案,并意识到JavaScript原生Array.sort()缺乏性能...

我使用RadixSort implementation中的@Blindman67对数组进行排序并进行了简单循环,并在O(N)或O(N * log(N))上得分为100/100。

function solution(A) {
    A = radixSort(A);
    let min = 1;
    for (let i = 0; i <= A.length; ++i) {
      if (A[i] == min && min <= A.length) {
        min++;
      }
    }
    return min;
}

// RadixSort by: https://codereview.stackexchange.com/users/120556/blindman67
function radixSort(numbers) {
  function emptyBuckets() {          // empties buckets and adds contents back to workArray
    workArray.length = 0;
    for (i = 0; i < 10; i += 1) {   // could have used buckets forEach but this is quicker on average
      if (buckets[i].length > 0) {
        workArray.push(...buckets[i]);
        buckets[i].length = 0;
      }
    }
  }

  var i;                  // hoist declarations
  const results = [];     // array that holds the finnal sorted numbers
  const buckets = [[], [], [], [], [], [], [], [], [], []];  // buckets
  const workArray = [...numbers]; // copy the numbers
  var power = 0;                  // current digit as a power of ten
  var tenPow = 1;                 // ten to the power of power
  if (numbers.length <= 1) {        // if one or no items then dont sort
    return workArray;           // dont sort if there is no need.
  }
  // as numbers are sorted and moved to the result array the numbers
  while (workArray.length > 0) {
    for (i = 0; i < workArray.length; i += 1) { // for all numbers still being sorted
      if (workArray[i] < tenPow) {            // is the number samller than the current digit
        results.push(workArray[i]);         //Yes it is sorted then remove a put o nthe result array
      } else {
        // add to bucket. Use Math.floor and save complexity doing it in one statement line
        buckets[Math.floor(workArray[i] / tenPow) % 10].push(workArray[i]);
      }
    }
    power += 1;
    tenPow = Math.pow(10, power);
    emptyBuckets();
  }
  return results;
}

答案 24 :(得分:0)

另一种实现方式::

  1. 对数组进行排序并获得数组的最低位数。

  2. 递增最低位数并检查是否已存在。

  3. 返回最低的正整数。

知道了!

//var A =[1,3,4,10];
var i =0;
var solution = function(A) {
var min = 0;
var max = 0;
sortedArray = A.sort(function(a, b){return a-b});
min =sortedArray[0]; //min value
max =sortedArray[sortedArray.length-1];//max value in array

if(min < 0){
alert("min is 1"); //use return 1
}
else if(min > 0){
for(;i<sortedArray.length;i++){
x = checkifNoExists(min+i+1);//start checking the no. with min  
if(x){
    var lowest = min+i+1
    break;
}
}
alert(lowest);//use return lowest
}
}
checkifNoExists = function(no){//to check if no exists in array
for(var y = 0;y<sortedArray.length;y++){
if(sortedArray[y] == no){
var found = no
}
}
if(found == "" || found == undefined){
return true;
}else{
return false;
}   
}       

答案 25 :(得分:0)

你可以试试这个:我用C#

static void Main(string[] args)
{

    int[] tempArray = new int[1000000];
    int[] givenArray = new int[] { 1, 2,3};   // or     { 1, 2,6,4,3}

    int results = myFunction(tempArray, givenArray);
    Console.WriteLine(results);
    Console.ReadKey();
}

private static int myFunction(int[] tempArray, int[] givenArray)
{
    int res = 0;

    for (int x = 1; x < tempArray.Length; x++)
    {

        if (!givenArray.Contains(x))
        {
            tempArray[x] = x;
        }
    }

    for (int y = 0; y < tempArray.Length; y++)
    {
        if (tempArray[y] > 0)
        {
            res = tempArray[y];
            break;
        }
    }
    return res;
}

答案 26 :(得分:0)

我通过此解决方案得到了100%

function solution(A) {
    let  sortedOb={};
    let biggest=0;
    A.forEach(el=>{
        if(el>0)
        {
             sortedOb[el]=0;
              biggest =  el>biggest? el:biggest
        }
    });
    let arr = Object.keys(sortedOb).map(el=>+el);
    if(arr.length==0)
    return 1;
    for(let i = 1; i<=biggest; i ++){
        if(sortedOb[i] === undefined)
        return i
    }
    return biggest+1
}

答案 27 :(得分:0)

我的解决方案:

function solution(A) {
// write your code in JavaScript (Node.js 6.4.0)
var B = A.sort(function(a,b){return a-b});
if(A.length == 1) {
    if(A[0] > 0) {
        if(A[0]>1) {
            return 1
        } else {
            return A[0]+ 1;    
        }
    } else {
        return 1   
    }
} else if(A.length > 1) {
    let max = Math.max.apply(null,A);
    let min = Math.min.apply(null,A);
    if(max > 0) {
        if(B[0]-0 > 1) { //for arrays that have a minimum higher than 1
            return 1
        }
        for(i=0;i<B.length-1;i++) { 
            if(B[i+1]- B[i] > 1){ //check the difference between next and current number, we also ignore the case of [x,-1,1,x2], since if a 0 is omitted, 1-(-1) will make 0 the highest missing number
                if(B[i] == -1 && B[i+1] == 1) {
                    //do nothing
                } else {
                    if(B[i]>0) {
                        return B[i]+1; //if the first number is positive, we can say the number after it is the smallest possible integer
                    } else {
                        return 1
                    }
                }   
            } 
        }
        return max + 1;
    } else {
        return 1
    }

} else {
    return null;
}
}

答案 28 :(得分:0)

我认为您的解决方案不正确,因为您使用了排序。排序是一个O(n * log(n))操作,他们要求一个时间和空间复杂度为O(n)的解决方案。

答案 29 :(得分:-1)

在JavaScript中

第一个解决方案:

function solution(A) {
  for (i = 1; i < 1000000; i++) {
    if(!A.includes(i)) return i;
  }
}

第二个解决方案:

function solution(A) {
  const set = new Set(A);
  let i = 1;
  while (set.has(i)) {
    i++;
  }
  return i;
}

第三个解决方案:

function solution(A){
    A = A.sort(); 
    for (var i=0;i<A.length-1;i++){
        if(A[i]>0 && A[i+1]!=(A[i]+1))
            return (A[i]+1);
    }
}