简体   繁体   English

查找三个数字之和可被给定数字整除的数字

[英]Finding three numbers whose sum is divisible by a given number

How can I search through an array and find every combination of three values whose sum is divisible by a given number(x) in java. 如何在数组中搜索并找到三个值的每个组合,这些值的总和可被java中的给定number(x)整除。

In other words, every combination where (n1+n2+n3) % x == 0. 换句话说,(n1 + n2 + n3)%x == 0的每个组合。

I know this would be a simple solution using a triple for loop but I need something with a time complexity of O(N^2). 我知道这是使用三重for循环的简单解决方案,但我需要时间复杂度为O(N ^ 2)的东西。

Any idea's? 有任何想法吗?

1 - Hash every (element % x) in the list. 1-哈希列表中的每个(元素%x)。

2 - Sum every pair of elements in the list (lets call the sum y) and do modded_y = y % x. 2-对列表中的每对元素求和(将其称为和y),并执行modded_y = y%x。

3 - Check if x - modded_y is in the hash table. 3-检查x-modded_y是否在哈希表中。 If it is and it's not one of the other 2 numbers then you found a possible combination. 如果是,并且不是其他两个数字之一,那么您找到了可能的组合。 Keep iterating and hashing the combinations you found so that they don't repeat. 继续迭代并哈希找到的组合,以免重复。

This is called a meet in the middle strategy. 这被称为中间策略会议。

It's complexity is O(n + (n^2 * 1)) = O(n^2) 它的复杂度是O(n +(n ^ 2 * 1))= O(n ^ 2)

I will call the given array A1. 我将给定的数组称为A1。

1) create two structs 1)创建两个结构

 struct pair{ int first; int second; bool valid; } 

 struct third{ int value; int index; } 

2) using a nested loop, initialize an array B1 of all possible Pairs. 2)使用嵌套循环,初始化所有可能对的数组B1。

3) Loop through B1. 3)循环通过B1。 if (A1[B1[i].first] + A1[B1[i].second])%x==0 then set B1[i].valid to true 如果(A1 [B1 [i] .first] + A1 [B1 [i] .second])%x == 0,则将B1 [i] .valid设置为true

4) create an array A3 of Thirds that stores the index and value of every element from A1 that is divisible by x. 4)创建一个三分之一数组A3,该数组存储A1中每个元素的索引和值,这些元素可以被x整除。

5) using a nested loop, go through each element of A3 and each element of B1. 5)使用嵌套循环,遍历A3的每个元素和B1的每个元素。 If B1.valid = true print A1[B1[i].first] and A1[B1[i].second] with an element from A1[A3.index]. 如果B1.valid = true,则使用来自A1 [A3.index]的元素打印A1 [B1 [i] .first]和A1 [B1 [i] .second]。

that should give you all combinations without using any triple loops. 应该可以为您提供所有组合,而无需使用任何三重循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM