LeetCode368. 最大整除子集

题目

给出一个由无重复的正整数组成的集合,找出其中最大的整除子集,子集中任意一对 (Si,Sj) 都要满足:Si % Sj = 0 或 Sj % Si = 0。
如果有多个目标子集,返回其中任何一个均可。
示例 1:
输入: [1,2,3]
输出: [1,2] (当然, [1,3] 也正确)
示例 2:
输入: [1,2,4,8]
输出: [1,2,4,8]

分析

在这里插入图片描述pre数组保存上一个可以整除的数字的索引(这个数字是count最大的数字),count数组统计数组中截止到每个数字时的最多的除数子集数量,max是个变量,随时更新最大的子集数量,maxIndex也是变量,它随着max更新,最大子集数的最后一个数字的索引。
然后可以通过maxIndex和pre数组,来找到符合情况的子集。

代码

class Solution {
    public List<Integer> largestDivisibleSubset(int[] nums) {
        LinkedList<Integer> result = new LinkedList<Integer>();
        int len = nums.length;
        if( len == 0 ) return result;
        int[] pre = new int[len];
        int[] count = new int[len];
        int max = 0;
        int maxIndex = 0;
        Arrays.fill(pre,-1);
        Arrays.sort(nums);

        for (int i = 1; i < len; i++) {
            for (int j = i-1; j >= 0; j--) 
                if (nums[i] % nums[j] == 0){
                    pre[i] = count[i] <= count[j] ? j : pre[i] ;
                    count[i] = count[i] <= count[j] ? count[j] + 1 : count[i];
                }     
            if(max < count[i]+1){
                max = count[i]+1;
                maxIndex = i;
            }
        }   
        int index = maxIndex;
        while(index != -1){
            result.addFirst(nums[index]);
            index = pre[index];
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值