34
loading...
This website collects cookies to deliver better user experience
nums
, we need to return the third maximum number from the array. If the third maximum does not exist then return the maximum number from the remaining elements.const thirdMax = function(nums) {
nums.sort(function(a,b){
return a - b;
});
console.log("sorted array values", nums);
}
pop()
method:-if(nums.length >= 3) {
return nums[nums.length - 3];
} else {
return nums.pop();
}
nums
array, but every time we make a push, we will check if the secondary array already contains that value. This way only distinct values will be added to the array as shown below:-const numsWithoutDuplicates = [];
nums.map((element, index)=>{
if(numsWithoutDuplicates.includes(element) === false) {
numsWithoutDuplicates.push(element);
}
});
const thirdMax = function(nums) {
nums.sort(function(a,b){
return a - b;
});
// console.log("sorted array values", nums);
const numsWithoutDuplicates = [];
nums.map((element, index)=>{
if(numsWithoutDuplicates.includes(element) === false) {
numsWithoutDuplicates.push(element);
}
});
// console.log("numsWithoutDuplicates", numsWithoutDuplicates);
if(numsWithoutDuplicates.length >= 3) {
return numsWithoutDuplicates[numsWithoutDuplicates.length - 3];
} else {
return numsWithoutDuplicates.pop();
}
};