在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand. Return True if the array is good otherwise return False. Example 1: Input: nums = [12,5,7,23] Input: nums = [29,6,10] Input: nums = [3,6] Constraints: 1 <= nums.length <= 10^5 给你一个正整数数组 nums,你需要从中任选一些子集,然后将子集中每一个数乘以一个 任意整数,并求出他们的和。 假如该和结果为 1,那么原数组就是一个「好数组」,则返回 True;否则请返回 False。 示例 1: 输入:nums = [12,5,7,23] 输入:nums = [29,6,10] 输入:nums = [3,6] 提示: 1 <= nums.length <= 10^5 Runtime: 456 ms
Memory Usage: 23.8 MB
1 class Solution { 2 func isGoodArray(_ nums: [Int]) -> Bool { 3 var nums = nums 4 var x:Int = nums[0] 5 var y:Int = 0 6 for i in 0..<nums.count 7 { 8 while(nums[i] > 0) 9 { 10 y = x % nums[i] 11 x = nums[i] 12 nums[i] = y 13 } 14 } 15 return x == 1 16 } 17 } 468ms 1 class Solution { 2 func isGoodArray(_ nums: [Int]) -> Bool { 3 if nums.isEmpty { 4 return false 5 } 6 7 var res = 0 8 for num in nums { 9 res = gcd(res, num) 10 } 11 12 return res == 1 13 } 14 15 func gcd(_ a: Int, _ b: Int) -> Int { 16 if a == 0 { 17 return b 18 } else { 19 return gcd(b % a, a) 20 } 21 } 22 }
|
请发表评论