【问题标题】:Balance two arrays of integers evenly平衡两个整数数组
【发布时间】:2021-12-13 11:17:33
【问题描述】:

我有两个整数数组。我正在寻找一种算法来平衡两个数组上两个数组的数字之和(尽可能准确)。

数字应该以这样的方式分布在数组之间,即存在平衡并且两个数组具有相同的数字总和。如果无法分配,则应输出差异。

最后,两个数组中的数值应该相同(不是整数的个数)。 在所示情况下,解决方案很简单,因为只需要移动一个数字。但是,也有一些复杂的情况,数字必须在“两个方向”上移动才能达到平衡。

这里最好的解决方案是什么?

非常感谢。

【问题讨论】:

  • 我不清楚您的要求。你到底从什么开始,你希望输出什么?
  • @user3386109 抱歉,图片当然是错误的。我换了个图再上传。
  • @khelwood 我从两个整数数组开始,输出应该是两个数值之和相等的数组。
  • 你的新图表清晰了很多。
  • 这被称为分区问题。也可以将其视为子集和问题,方法是将两个数组中的所有元素相加并除以 2 以获得目标和。不幸的是,这两个问题的维基百科页面没有提供有关动态编程解决方案的详细信息,因此您必须在谷歌上搜索这些名称以查看是否可以找到伪代码。

标签: java arrays algorithm integer balance


【解决方案1】:
  • 只需创建一个数组并在其中填充两个数组值。
  • 使用分区相等子集和。

解决方案-1:(如果您只想检查是否可能,请使用此)

def canPartition(self, nums: List[int]) -> bool:
        total = sum(nums)
        if(total%2 == 1):
            return False
        size = len(nums)
        amount= total//2
        m = 1
        for n in nums:
            m |= (m << n)
        return (m >> amount) & 1

解决方案-2:(如果您想要数组值只需更新以下代码的逻辑)

def canPartition(self, nums: List[int]) -> bool:
    total = sum(nums)
    if(total%2 == 1):
        return False
    size = len(nums)
    amount= total//2
    total = [False for i in range(amount+1)]
    total[0] = True
    for j in nums:
        for i in range(amount,j-1,-1):
            if(i-j >=0):
                if(total[i-j]):
                    total[i] = True
    if(total[amount] == False):
        return False
    else:
        return total[amount]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 2020-11-01
    • 2011-08-28
    • 1970-01-01
    相关资源
    最近更新 更多