博客
关于我
最大整除子集
阅读量:120 次
发布时间:2019-02-26

本文共 1453 字,大约阅读时间需要 4 分钟。

文章目录

1、描述

给你一个由 无重复 正整数组成的集合 nums ,请你找出并返回其中最大的整除子集 answer ,子集中每一元素对 (answer[i], answer[j]) 都应当满足:

answer[i] % answer[j] == 0 ,或
answer[j] % answer[i] == 0
如果存在多个有效解子集,返回其中任何一个均可。

示例 1:

输入:nums = [1,2,3]

输出:[1,2]
解释:[1,3] 也会被视为正确答案。
示例 2:

输入:nums = [1,2,4,8]

输出:[1,2,4,8]

来源:力扣(LeetCode)

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2、关键字

数组,最大,

3、思路

dp两层遍历,求出最长子集的数量,然后使用两个临时变量记录个数,和最大值,

然后再遍历一遍nums,通过最大值和个数来抽取结果集。

4、notes

1、dp数组获取满足条件的个数,然后通过两个临时变量做一些记录,然后再遍历一遍原数组,进行结果集的调出。

2、最后获取结果集的元素的时候,需要满足两个条件,整除,且dp[i]也满足(最大的个数),

5、复杂度

时间:O(n平方)计算数组dp元素,排序是O(nlogn),倒序遍历是O(N)

空间:O(N),dp数组的长度

6、code

class Solution {   public:    vector
largestDivisibleSubset(vector
& nums) { int n = nums.size(); vector
dp (n,1); // 初始化为1 int maxVal = nums[0]; // 最大值 int maxSize = 1; // 结果集的个数 vector
res; sort(nums.begin(),nums.end()); // 排个序 for(int i = 1; i < n; i++){ for(int j = 0; j
=0; i--){ if(maxVal>=nums[i] && maxVal % nums[i] == 0){ res.push_back(nums[i]); } }*/ for (int i = n - 1;i >= 0,maxSize > 0; i--){ // 个数满足,从右往左 if(dp[i] == maxSize && maxVal % nums[i] == 0){ // 个数满足,且符合整除,这两个条件才是一个结果 res.push_back(nums[i]); maxVal = nums[i]; // 这里不写就错,更新最大值,变得越来越小 maxSize--; // 这里也更新一下 } } return res; }};
你可能感兴趣的文章
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>