Algorithm 从数组(X1,X2,Y)中查找三元组,使X1*X2=Y^2
如何找到三胞胎,形成一个数组 (X1,X2,Y) 以致 X1*X2=Y2 结果中不能有任何重复,元素在105的范围内 我已经尝试过这样做,通过采用所有的组合,但我想要一种有效的方法…一个成本为O(N^2)的python实现(更紧凑、更可读)Algorithm 从数组(X1,X2,Y)中查找三元组,使X1*X2=Y^2,algorithm,Algorithm,如何找到三胞胎,形成一个数组 (X1,X2,Y) 以致 X1*X2=Y2 结果中不能有任何重复,元素在105的范围内 我已经尝试过这样做,通过采用所有的组合,但我想要一种有效的方法…一个成本为O(N^2)的python实现(更紧凑、更可读) 导入数学 输入列表=[1,2,18,7,6,22,4,8,65] 平方_y={x**2代表输入_列表中的x}#这将是一个具有O(1)查找的集合 解决方案=集合() 对于索引,枚举中的x1(输入列表): 对于输入列表中的x2[索引+1:]: 如果x1*x2的平
导入数学
输入列表=[1,2,18,7,6,22,4,8,65]
平方_y={x**2代表输入_列表中的x}#这将是一个具有O(1)查找的集合
解决方案=集合()
对于索引,枚举中的x1(输入列表):
对于输入列表中的x2[索引+1:]:
如果x1*x2的平方为y:
解决方案。添加((x1,x2))
解决方案。添加((x2,x1))
对于溶液中的溶胶:
如果sol[0]使用Java的HashMap
仅当x1*x2
为正方形时,从数组中取出所有x1,x2
对,并作为[y[x1,x2]]
插入到映射中。这消除了许多组合,减少了内存需求,减少了后面部分的比较
然后循环遍历与数组元素匹配的映射键值
这是O(n^2)
定时复杂性
public class FindTriplets
{
final static int isSquare(long n)
{
int tst = (int) (Math.sqrt(n) + 0.5);
if ((tst * tst) == n)
return tst;
else
return 0;
}
static void findTriplets(int[] nums)
{
Map<Integer, List<Integer>> triplets = new HashMap<Integer, List<Integer>>();
int n = nums.length;
// insert into a Map as {y, [x1, x2]} when y*y = x1*x2, x1 & x2 are elements of nums
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
int y = isSquare(nums[i] * nums[j]);
if (y != 0)
{
List<Integer> x1x2 = new ArrayList<Integer>(Arrays.asList(nums[i], nums[j]));
triplets.put(y, x1x2);
}
}
}
// Now look for elements nums[i] matching with y in the Map
for (int i = 0; i < n; i++)
{
if (triplets.containsKey(nums[i]))
{
List<Integer> x1x2 = triplets.get(nums[i]);
System.out.println(x1x2.toString() + " -> " + nums[i]);
}
}
}
public static void main(String[] args)
{
int[] num = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 18 };
findTriplets(num);
}
}
因为一个数字Y可以x1,x2,Y
重复?例如,对于{1,1,2,3}
来说1*1==1**2
是有效的解决方案吗?请注意,我们在解决方案中有3
1
s,但在阵列中只有2
不允许重新配置查找边界,如果x相同,则应该只有一个比率解决方案。Sqrt(3x)=y@RussianBoy-数组值的范围是多少?@RussianBoy首先,如果有人试图帮助您,请在线或挂断。第二,输入数组中是否不存在重复项,或者您不希望在最终输出中出现重复项?此外,x1,x2,y
是否应该具有不同的索引i,j,k
其中i!=j!=k
?您可能还希望消除重复的三胞胎。@vivek_23 OP声明没有重复,因此不会有重复repetition@vivek_231(作为x1)是数组的元素,4(作为x2)是数组的元素,4(作为y^2)是元素2的平方。我看不到repetition@MarcoZamboni@Armali我看到这个问题是问X1,X2和Y,所以我将进行编辑,以匹配I如何在O(1)中从Y的因子传递到Y^2的因子?例如6:{1,2,3,6}的因子,夫妇:{(1,6),(2,3)}。那么36个因素:{1,2,3,4,6,9,12,18,36},夫妇:{(1,36),(2,8),(3,12),(4,9),(6,6)}对记忆的要求如何?考虑{2,3,4,5,6,7,8,9,10,11,12,14,15,16,18}的数组;您不需要记住所有的因子分解或因子对。在生成它们时检查它们,这样就只会有大小不一的散列映射
[2, 8] -> 4
[4, 9] -> 6
[4, 16] -> 8
[9, 16] -> 12