Araays
Task
Complete the getSecondLargest function in the editor below. It has one parameter: an array, $nums$, of $n$ numbers. The function must find and return the second largest number in $nums$.
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, $n$, denoting the size of the $nums$ array. The second line contains $n$ space-separated numbers describing the elements in $nums$.
Constraints
- $1 < n < 10$
- $0 < nums < 100$, where $nums$, is the number at index $i$.
- The numbers in $nums$ are not distinct.
Output Format
Return the value of the second largest number in the $nums$ array.
Sample Input
5
2 3 6 6 5
Sample Output
5
Dev
'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 firstBigNum = 0, secondBigNum = 0;
for (const num in nums) {
if (firstBigNum < nums[num]) {
if (firstBigNum > secondBigNum) {
secondBigNum = firstBigNum;
}
firstBigNum = nums[num];
} else if (firstBigNum != nums[num]) {
if (secondBigNum < nums[num]) {
secondBigNum = nums[num];
}
}
}
return secondBigNum;
}
Study
Java 향상된 for문과 Javascript 향상된 for문이 헷갈려 당황했다.
int[] s = {2, 13, 45, 65 ,45};
for(int i : s) {
System.out.println(i);
}
const s = [2, 13, 45, 65, 45];
for (const i in s) {
console.log(s[i]);
}
js에서 향상된 for문은 배열의 요소가 아닌 인덱스를 가져온다.