Given an integer array, nums return the greatest common divisor of the smallest number and the 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.
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.
Approach 1:
Using Sorting (min element will be the first element and max element will be the last element).
Time Complexity: O(Nlog(N))
Java
import java.util.Arrays;public class GCDArrayUsingSorting {public static void main(String[] args) {int[] nums = { 2, 5, 6, 9, 10 };System.out.println(findGCD(nums));}static int gcd(int a, int b) {if (b == 0)return a;return gcd(b, a % b);}static int findGCD(int[] nums) {Arrays.sort(nums);int minElement = nums[0], maxElement =nums[nums.length - 1];return gcd(minElement, maxElement);}}
C++
#include <bits/stdc++.h>using namespace std;int gcd(int a, int b){if (b == 0)return a;return gcd(b, a % b);}int findGCD(vector<int> &nums){sort(nums.begin(), nums.end());int minElement = nums[0], maxElement = nums[nums.size() - 1];return gcd(minElement, maxElement);}int main(){vector<int> nums = {2, 5, 6, 9, 10};cout << findGCD(nums) << "\n";return 0;}
Approach 2:
Find minimum element and maximum element by iterating through all elements of the array.
Time Complexity: O(N)
Java
public class GCDArray {public static void main(String[] args) {int[] nums = { 2, 5, 6, 9, 10 };System.out.println(findGCD(nums));}static int gcd(int a, int b) {if (b == 0)return a;return gcd(b, a % b);}static int findGCD(int[] nums) {int minElement = nums[0], maxElement = nums[0];for (int i = 1; i < nums.length; i++) {minElement = Math.min(minElement, nums[i]);maxElement = Math.max(maxElement, nums[i]);}return gcd(minElement, maxElement);}}
C++
#include <bits/stdc++.h>using namespace std;int gcd(int a, int b){if (b == 0)return a;return gcd(b, a % b);}int findGCD(vector<int> &nums){int minElement = nums[0], maxElement = nums[0];for (int i = 1; i < nums.size(); i++){minElement = min(minElement, nums[i]);maxElement = max(maxElement, nums[i]);}return gcd(minElement, maxElement);}int main(){vector<int> nums = {2, 5, 6, 9, 10};cout << findGCD(nums) << "\n";return 0;}
No comments:
Post a Comment