var firstMissingPositive = function(nums) {
nums = nums.sort(function(val1, val2) {
return val1>val2?1:val1<val2?-1:0;
});
if(nums.length===0||nums[nums.length-1]<=0){ return 1; } // A, B
for(var i=0,k=1; i<nums.length; ++i){ // C
if(nums[i]>k){ return k; }
k = nums[i]<k?k:k+1;
}
return nums[nums.length-1]+1; // D
};
var firstMissingPositive = function (nums) {
let s = 1;
let i = 0;
let w = false;
do {
w = false;
for (i = 0; i < nums.length; i++) {
if (s == nums[i]) {
s++;
w = true;
}
}
} while (w == true)
return s
};
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
A | |
V |
Test name | Executions per second |
---|---|
A | 1098003712.0 Ops/sec |
V | 1095118080.0 Ops/sec |
Benchmark Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The provided benchmark definition consists of two test cases, each with its own script preparation code and HTML preparation code. The goal of the benchmark is to measure which approach performs better in finding the first missing positive integer in an array.
Test Case 1: A
The script preparation code for Test Case A is:
var firstMissingPositive = function(nums) {
nums = nums.sort(function(val1, val2) {
return val1>val2?1:val1<val2?-1:0;
});
if(nums.length===0||nums[nums.length-1]<=0){ return 1; }
for(var i=0,k=1; i<nums.length; ++i){
if(nums[i]>k){ return k; }
k = nums[i]<k?k:k+1;
}
return nums[nums.length-1]+1;
};
This script uses the following approaches:
sort()
.k
. If found, return k
as the first missing positive integer. Otherwise, increment k
by 1.Test Case 2: V
The script preparation code for Test Case V is:
var firstMissingPositive = function (nums) {
let s = 1;
let i = 0;
let w = false;
do {
w = false;
for (i = 0; i < nums.length; i++) {
if (s == nums[i]) {
s++;
w = true;
}
}
} while (w == true)
return s;
};
This script uses the following approaches:
s
and i
, to 1 and 0 respectively.s
by 1 in each iteration if it matches an element in the array. If no match is found, set w
to true.s
. If found, increment s
by 1 and set w
to false.Comparison of Approaches
Here are some pros and cons of each approach:
Test Case A (Approach A):
Test Case V (Approach V):
Other Alternatives
Some alternative approaches to finding the first missing positive integer in an array include:
Library Usage
Neither of the provided scripts uses any external libraries. However, if you choose to use a library, some popular options include:
Special JS Features or Syntax
The provided scripts do not use any special JavaScript features or syntax. However, some examples of advanced techniques that can be applied to this problem include: