1.문제
Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums.
The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.
정수 배열 nums가 주어질 때 nums에서 최솟값과 최댓값의 최대공약수를 리턴하는 문제이다.
Example 1
Input: nums = [2,5,6,9,10]
Output: 2
Explanation:
The smallest number in nums is 2.
The largest number in nums is 10.
The greatest common divisor of 2 and 10 is 2.
Example 2
Input: nums = [7,5,6,8,3]
Output: 1
Explanation:
The smallest number in nums is 3.
The largest number in nums is 8.
The greatest common divisor of 3 and 8 is 1.
Example 3
Input: nums = [3,3]
Output: 3
Explanation:
The smallest number in nums is 3.
The largest number in nums is 3.
The greatest common divisor of 3 and 3 is 3.
Constraints:
- 2 <= nums.length <= 1000
- 1 <= nums[i] <= 1000
2.풀이
- nums에서 최솟값과 최댓값을 저장한다.
- 어떤 두 수의 최대공약수는 두 수중 작은 값보다 클 수 없다.
- nums의 최소값까지 for문을 돌면서 최솟값과 최댓값을 모두 나누는 수를 찾아서 result에 넣는다.
- result의 마지막 요소를 리턴한다.
/**
* @param {number[]} nums
* @return {number}
*/
const findGCD = function (nums) {
const result = [];
// 오름차순으로 정렬한다.
nums.sort((a, b) => a - b);
const largest = nums.pop();
const smallest = nums.shift();
// 두 수 중 작은수까지 반복문을 돌면서 두 수를 모두 나눌 수 있는 수이면 result에 push
for (let i = 1; i <= smallest; i++) {
if (smallest % i === 0 && largest % i === 0) {
result.push(i);
}
}
// 최대값 리턴하기
return result.pop();
};
3.결과
