[英]How can I (more) easily compare two sets of numbers?
我有一组三个数字,我想将一组数字与另一组数字进行比较。 即,第一组中的每个数字小于另一组中的至少一个数字。 需要注意的是,第一组中的下一个数字必须小于第二组中的另一个数字(即{6,1,6}将对{8,8,2}起作用,但是{6,2,6 }对{8,8,2}不会)。 我有一个可行的方法,但这是蛮力和丑陋的。
如果我们有setA和setB,并且每个元素都有元素a,b和c:
if(setB.a < setA.a)
if(setB.b < setA.b)
if(setB.c < setA.c)
return true;
else if(setB.b < setA.c)
if(setB.c < setA.b
return true;
等等...
编辑:我刚刚意识到你说这些集被硬编码为3个值。 这是适用于任何大小集的超通用算法。
对于三值集,可以对集合元素进行相同的转储和排序,然后执行以下操作:
if(setB.a < setA.a)
if(setB.b < setA.b)
if(setB.c < setA.c)
return true;
return false;
================================================== ====
通用算法:
这是我可以立即想到的最有效的方法。
伪代码(比Java更具pythonic,抱歉-希望注释能够解释):
list l1 = set1.items() //get the items out
list l2 = set2.items()
l1 = sort(l1)
l2 = sort(l2) //sort the lists
int set2idx1 = l1[0].find_closest_greater_than_value(l2) //binary search or something
if set2idx1 exists:
l2 = l2[set2idx1+1:] //in python this means l2 is reassigned to a subarray of l2 starting at set2idx1+1 going to the end of l2
else:
return false
for(int i=1; i<l1.len; i++)
int set2idxi = l1[i].find_closest_greater_than_value(l2) //binary search or something
if set2idxi exists:
l2 = l2[set2idxi+1:]
else
return false
return true
评论什么都没有道理
编辑编辑:
对任何有关方面的一般算法的说明:
这里的想法是,由于对数组进行了排序,因此您知道,比第二个数组中的匹配元素大的任何元素都将大于您要针对第一个数组中的元素进行测试的元素。 因此,您可以仅剔除较低的值,并且由于您不想使用相同的值,因此也可以剔除找到的值。 如果返回false,那是因为没有更大的值,或者是因为array1中的数字都大于array2中的数字,或者是因为array2中的数字没有大于array1中的数字。
那么下面的伪代码呢?
Condition(A : Set, B : Set) : Bool =
Let a := max(A), b := min(B) In
// Namely, that each number in the first set is less than at least one number in the other set
If a <= b Then
// the next numbers in the first set must be less than a different number in the second set
Condition(without(A, a), without(B, b))
Else
False
EndIf
如果没有(A,a)表示集合A减去集合{a}
由于您的示例包含重复元素,因此List
似乎比Set
更好。 只是:
1)对两个列表进行排序。
2)修剪掉第二个列表中的前几个元素,直到第一和第二个列表的大小相等。
3)对每个i
直接将list1[i]
与list2[i]
比较。
码:
import java.util.*;
class Main {
public static void main (String[] args) {
List<Integer> list1 = new ArrayList<Integer>();
List<Integer> list2 = new ArrayList<Integer>();
list1.add(3); list1.add(7); list1.add(7);
list2.add(8); list2.add(8); list2.add(2); list2.add(1); list2.add(5);
//algorithm:
Collections.sort(list1);
Collections.sort(list2);
List<Integer> list3 = list2.subList(list2.size() - list1.size(), list2.size());
System.out.println(list1.size() + " " + list3.size());
boolean pass = true;
for(int i = 0; pass && i < list1.size(); i++)
if(list1.get(i) >= list3.get(i))
pass = false;
System.out.println(pass);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.