查找具有最小成员变量的对象

时间:2014-03-24 14:14:12

标签: java android algorithm

好的,所以我想找到一个搜索一些对象的algorythm(在我的例子中为4)并找到具有最小成员变量的对象。假设您可以使用object.getIntegerValue()

获得该值

在我的情况下,我有4个Android布局,并希望找到具有最少量孩子的布局。

我认为会有很多解决方案,但我只想找到一个快速的解决方案。无论多脏等等......

到目前为止我的代码很简短,很脏并且总是返回具有最小成员变量的对象,但是这里只需要作为代码示例:

private LinearLayout layoutChanger(){
    int one, two, three;
    one = layoutOne.getChildCount();
    if ((two = layoutTwo.getChildCount()) <= one) {
        if ((three = layoutThree.getChildCount()) <= two) {
            if ((layoutFour.getChildCount()) <= three)
                return layoutFour;
            return layoutThree;
        }
        return layoutTwo;
     }
     return layoutOne;
 }

修改 我知道如何做到这一点我宁愿想得到关于如何加快事情的建议......

Comparable真的很快吗?或者我应该将自己与OOP解决方案区分开来以获得更好的性能?

3 个答案:

答案 0 :(得分:3)

只是一个例子:

    int childCount;
    Layout[] myLayouts = {layoutOne,layoutTwo,layoutThree};
    Layout selected;
    for(Layout layout:myLayouts){
        if(childCount=0 || childCound>layout.getChildCount()) {
            selected = layout;
            childCount = layout.getChildCount();
        }
    }
    return layout;

答案 1 :(得分:1)

以下是不是 Java代码,这只是(Java like)伪代码给OP一个想法......

lowestPossibleValue = ?;
currentLowestValue = MAX;
foreach (object : collection) {
    if (object.getValue == lowestPossibleValue) {
        foundObject = object;
        break;
    } else {
        if (object.getValue < currentLowestValue) {
            foundObject = object;
        }
    }
}

// foundObject包含结果

答案 2 :(得分:0)

private LinearLayout layoutToggler(LinearLayout[] layoutArr){
        int currentChildCount;
        int minChildCount = MAX_VAL;
        LinearLayout retLayout = null;
        for(LinearLayout layout:layoutArr){
            if((currentChildCount = layout.getChildCount()) == MIN_VAL ){
                retLayout = layout;
                break;
            }
            else if(currentChildCount < minChildCount) {
                retLayout = layout;
                minChildCount = currentChildCount;
            }
        }
        return retLayout;
    }

感谢阿灵顿,因为他的想法被带到了一个有效的解决方案。