Find Greatest Common Divisor of Array (LeetCode)
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.
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.
Solution(Java):
class Solution {
public int findGCD(int[] nums) {
Arrays.sort(nums);
int n= nums.length-1, temp=1;
for(int i=2;i<=nums[n];i++){
if(nums[0]%i==0 && nums[n]%i==0){
if(i>temp)
temp= i;
}
}
return temp;
}
}
Comments
Post a Comment