숫자배열 중 두번째로 큰 수 추출하기
조건
- getSecondLargest 함수를 수정하여 두번째로 큰 수를 전달하라.
- parameters
- int nums[n]: 정수 배열
- Returns
- int: nums 에서 두번째로 큰 수
제한사항
- 1 ≤ n ≤ 10
- 0 ≤ nums[i] ≤ 100,
- i는 index
- nums의 숫자는 중복일 수 있음.
나의 풀이
- nums 배열에서 가장 큰 수를 추출 (max)
- nums 배열을 순회하며 max 가 아닌 값 중 가장 큰 수를 추출
- reduce 함수를 이용하여 바로바로 값을 비교처리함
// 생략...
/**
* 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) {
// Complete the function
var max = Math.max(...nums);
var second_max = nums.reduce((a, b) => {
if (b != max) {
a = Math.max(a, b);
}
return a;
}, 0);
return second_max;
}
// 후략...
결과
'HackerRank' 카테고리의 다른 글
[해커랭크] Day 6: Bitwise Operators (javascript) (0) | 2022.08.19 |
---|---|
[해커랭크] Day 5: Template Literals (javascript) (0) | 2022.08.19 |
[해커랭크] Day 8: Buttons Container (javascript) (0) | 2022.08.18 |
[해커랭크] Day 7: Regular Expressions Ⅰ(javascript) (0) | 2022.08.18 |
[해커랭크] Day 5: Inheritance (javascript) (0) | 2022.08.18 |