Last active
April 29, 2019 12:04
-
-
Save quangnd/e9a98f3103a5f0eb740ac44a6f2d8292 to your computer and use it in GitHub Desktop.
Find the second largest number in array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Write a function named getSecondLargest. This function has one parameter: an array of numbers. The function must find and return the second largest number in. | |
Sample input | |
` | |
nums = [2,3,6,6,5] | |
getSecondLargest(nums) | |
` | |
Sample output | |
`5` | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Return the second largest number in the array. | |
* @param {Number[]} nums - An array of numbers. | |
* @return {Number} The second largest number in the array. | |
**/ | |
// In 34 years old man's mind | |
function getSecondLargest(nums) { | |
let largestNum = findLargestNum(nums); | |
let filteredArr = nums.filter(num => num !== largestNum); | |
return findLargestNum(filteredArr); | |
} | |
function findLargestNum(nums) { | |
let largestNum = nums[0]; | |
for (let i = 0; i < nums.length; i++) { | |
if (largestNum < nums[i + 1]) { | |
largestNum = nums[i + 1]; | |
} | |
} | |
return largestNum; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Using Math.max built-in function | |
function getSecondLargest(nums) { | |
const max = Math.max(...nums) | |
return Math.max(...nums.filter(x => x !== max)) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Using only one for loop | |
function getSecondLargest(nums) { | |
let first = nums[0]; | |
let second = -1; | |
for (let i = 0; i < nums.length; i++) { | |
if (nums[i] > first) { | |
second = first; | |
first = nums[i]; | |
} | |
if (nums[i] > second && nums[i] < first) { | |
second = nums[i]; | |
} | |
} | |
return second; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment