日月换新天。为有牺牲多壮志,敢教

[Swift]LeetCode1250. 检查「好数组」| Check If It Is a Good Array

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(let_us_code)
➤博主域名:https://www.zengqiang.org
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/11831469.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新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]
Output: true
Explanation: Pick numbers 5 and 7.
5*3 + 7*(-2) = 1
Example 2:

Input: nums = [29,6,10]
Output: true
Explanation: Pick numbers 29, 6 and 10.
29*1 + 6*(-3) + 10*(-1) = 1
Example 3:

Input: nums = [3,6]
Output: false

Constraints:

1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9


给你一个正整数数组 nums,你需要从中任选一些子集,然后将子集中每一个数乘以一个 任意整数,并求出他们的和。

假如该和结果为 1,那么原数组就是一个「好数组」,则返回 True;否则请返回 False。 

示例 1:

输入:nums = [12,5,7,23]
输出:true
解释:挑选数字 5 和 7。
5*3 + 7*(-2) = 1
示例 2:

输入:nums = [29,6,10]
输出:true
解释:挑选数字 29, 6 和 10。
29*1 + 6*(-3) + 10*(-1) = 1
示例 3:

输入:nums = [3,6]
输出:false

提示:

1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9


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 }
复制代码

 

posted @   为敢技术  阅读(324)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示
哥伦布
15°
14:09发布
哥伦布
14:09发布
15°
中雨
西南风
5级
空气质量
相对湿度
88%
今天
中雨
5°/16°
周一
小雨
0°/11°
周二
4°/19°