我有两个对象数组;
namesArr[col][row] = new names("String",x,y); //Text Array
rectangleArr[col][row] = new rectangle(x,y); //awt.Rectangle Array
我只是想确定两个元素存在的点,不是元素是否存在。内容相等。例如,将交点与样本数据进行比较时:
namesArr[0][1]= new names("Myname",1,2)
namesArr[0][2]= NULL
namesArr[3][4]= new names("notMyname",4,6)
rectangleArr[0][1] = new recatngle(7,8)
算法应该返回[0] [1]处只存在一个交集。
答案 0 :(得分:1)
我通常会与@Ben一起投票。但是,如果必须这样做,并且必须有效地完成,我认为你应该从数组切换到地图:
import java.awt.Point;
import java.awt.Rectangle;
import java.util.HashMap;
import java.util.Map;
public class Demo {
public static void main(String... args) {
Map<Point,String> names=new HashMap<>();
Map<Point,Rectangle> rectangles=new HashMap<>();
names.put(new Point(0,1), "my name");
names.put(new Point(0,2), null);
names.put(new Point(1,4), "not my name");
rectangles.put(new Point(0,1),new Rectangle(7, 8));
//find matches
for(Point i:names.keySet()){
if(rectangles.containsKey(i)){
System.out.println("intersection at "+i);
}
}
}
}
这应该可以在数组方法的n ^ 2运行时下很好地使用。
这是一个包含David Conrad优化的util函数:
public static <Key> Set<Key> getIntersectingKeys(Map<Key, ?> map1, Map<Key, ?> map2) {
Set<Key> ret, other;
if (map1.size() < map2.size()) {
ret = new HashSet<>(map1.keySet());
other = map2.keySet();
} else {
ret = new HashSet<>(map2.keySet());
other = map1.keySet();
}
Iterator<Key> it = ret.iterator();
while (it.hasNext()) {
Key i = it.next();
if (!other.contains(i)) {
it.remove();
}
}
return ret;
}
答案 1 :(得分:0)
试试这个:
ArrayList<String> intersections = new ArrayList<String>();
for(int namesArrCounter = 0; namesArrCounter < namesArr.length; namesArrCounter++ ){
for(int namesArrColCounter = 0; namesArrColCounter < namesArr[namesArrCounter].length; namesArrColCounter++){
if(namesArrCounter < rectangleArr.length && namesArrColCounter < rectangleArr[namesArrCounter].length){
if(rectangleArr[namesArrCounter][namesArrColCounter] != null){
intersections.add("["+namesArrCounter+"]"+"["+ namesArrColCounter +"]");
}
}
}
}
return intersections;