Last active
July 30, 2019 04:47
-
-
Save wataruoguchi/5066e1c09028f8ba4a17bf2af0ccaabc to your computer and use it in GitHub Desktop.
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
// https://practice.geeksforgeeks.org/problems/find-the-smallest-and-second-smallest-element-in-an-array/0 | |
function findTwoSmallest(arr) { | |
// 1<=n<=100 | |
let smallests = [101, 101]; // 1st smallest, 2nd smallest | |
const res = arr.reduce((acc, num) => { | |
if (num < acc[1] && num !== acc[0]) { | |
if (num < acc[0]) { | |
acc[1] = acc[0]; | |
acc[0] = num; | |
} else { | |
acc[1] = num; | |
} | |
} | |
return acc; | |
}, smallests); | |
return res.find((num) => num > 100) ? [-1] : res; | |
} | |
const nums1 = [2,4,3,5,6]; | |
const result1 = findTwoSmallest(nums1); | |
console.log(result1.join(',') === '2,3'); | |
const nums2 = [1,2,1,3,6,7]; | |
const result2 = findTwoSmallest(nums2); | |
console.log(result2.join(',') === '1,2'); | |
const nums3 = [1,1]; | |
const result3 = findTwoSmallest(nums3); | |
console.log(result3.join(',') === '-1'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment