[JAVASCRIPT][HackerRank]10 days of JS Day5


  1. Arrays

Task

Complete the getSecondLargest function in the editor below. It has one parameter: an array, , of numbers. The function must find and return the second largest number in .

Input Format

Locked stub code in the editor reads the following input from stdin and passes it to the function: The first line contains an integer, , denoting the size of the array. The second line contains space-separated numbers describing the elements in .

Constraints

  • , where is the number at index .
  • The numbers in are not distinct.

Output Format

Return the value of the second largest number in the array.

'use strict';

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) {
    // Complete the function
    let first = nums[0];
    let second;
    for(let i=1;i<nums.length;i++)
    {
        let num = nums[i];
        if (num > first)
        {
            second = first;
            first = num;
        }
        else
        {
            if (num > second && num < first)
                second = num;
        }
    }
    return second;
}


function main() {
    const n = +(readLine());
    const nums = readLine().split(' ').map(Number);
    
    console.log(getSecondLargest(nums));
}

array에서 두번째로 큰 수 구하는 문제.

이렇게는 한번도 생각해보지 않았어서 생각을 좀 했어야했다.

사람이야.. 숫자를 보는 순간 어떤것이 가장 크구나, 라고 바로 알지만, 기계입장에서는 숫자는 숫자이고..문자는 문자일 뿐이니..

비교를 해주어야했다.




© 2018. by sora

Powered by sora