Skip to content

Instantly share code, notes, and snippets.

@Seralahthan
Created July 5, 2020 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Seralahthan/87849e4394bc1b4fdd6f794c28b5830a to your computer and use it in GitHub Desktop.
Save Seralahthan/87849e4394bc1b4fdd6f794c28b5830a to your computer and use it in GitHub Desktop.
Find the second largest number of an array using loop
'use strict';
const { PerformanceObserver, performance } = require('perf_hooks');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
/**
* Return the second largest number in the array.
* @param {Number[]} nums - An array of numbers.
* @return {Number} The second largest number in the array.
**/
function getSecondLargest(nums) {
var numSet = new Set(nums);
var numArray = [...numSet];
var numArray = numArray.sort(function(a,b){return b-a});
return (numArray.length>1) ? numArray[1] : numArray[0];
}
/**
* Return the second largest number in the array.
* @param {Number[]} nums - An array of numbers.
* @return {Number} The second largest number in the array.
**/
function getSecondLargestLoop(nums) {
var largestNum = nums[0];
var secondLargestNum = nums[1];
var temp = 0;
var isEqual = false;
if (secondLargestNum > largestNum) {
temp = largestNum;
largestNum = secondLargestNum;
secondLargestNum = temp;
}
if (secondLargestNum === largestNum) {
isEqual = true;
}
for (let i=2; i < nums.length; i++) {
var indexVal = nums[i];
if (indexVal >= largestNum) {
secondLargestNum = largestNum;
largestNum = indexVal;
} else {
if (indexVal >= secondLargestNum) {
secondLargestNum = indexVal;
} else {
if(isEqual) {
secondLargestNum = indexVal;
}
}
}
if (secondLargestNum === largestNum) {
isEqual = true;
} else {
isEqual = false;
}
}
return secondLargestNum;
}
function main() {
const n = +(readLine());
const nums = readLine().split(' ').map(Number);
var t0 = performance.now();
console.log(getSecondLargest(nums));
var t1 = performance.now();
console.log("Time taken to execute the getSecondLargest() function : " + (t1-t0));
t0 = performance.now();
console.log(getSecondLargestLoop(nums));
t1 = performance.now();
console.log("Time taken to execute the getSecondLargestLoop() function : " + (t1-t0));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment