数组逻辑错误

时间:2012-05-05 11:26:28

标签: java arrays

我编写了以下代码来解决问题,但它不起作用。问题的链接是here

  public boolean linearIn(int[] outer, int[] inner) {

    boolean result = false;

        if(inner.length == 0)
            return true;

        index: for(int x: inner) {
                    for(int y: outer) {
                        if(x==y) {
                            result = true;
                            break;
                        }
                        else {
                            result = false;
                            break index;
                        }
                    }
                }
        return result;
    }

4 个答案:

答案 0 :(得分:4)

问题出在其他部分。你不能断定,如果只有一个比较失败,内部数组 中的元素

if(x==y) {
 result = true;  // ele present.
 break;
} else { 
 result = false; // can't conclude ele is absent..you might find it later.
 break index;
}

要解决此问题,您可以这样做:

public boolean linearIn(int[] outer, int[] inner) {

        for(int x: inner) {
                // assume x is absent.
                boolean result = false;
                for(int y: outer) {
                        // x found in outer.
                        if(x==y) {
                                // make result positive.
                                result = true;
                                // no need to look any further.
                                break;
                        }
                }
                // at this point not all elements of inner are 
                // tested for presence in outer. But one missing ele
                // would mean we return false.
                if(result == false) return false;
        }
        // all ele of inner are present in outer..return true.
        return true;
}

答案 1 :(得分:1)

如果复杂度应为O(n),则为假设代码:

public boolean linearIn (int[] outer, int[] inner) {

 int in=0;
    for(int i :outer){
        if(in==inner.length) return true;
        if(inner[in]==i)
            in++;}
    if(in==inner.length)return true;
    return false;
}

答案 2 :(得分:0)

你必须制作O(n)解决方案,你的是O(n 2 )。你只需要三行(OK,作弊):

int j = 0;
for (int in : inner) while (outer[j] != in) if (++j == outer.length) return false;
return true;

答案 3 :(得分:0)

这个想法是在外部循环并在内部循环内部 如果你看到它的中断,规则会立即返回false 如果在最后,内部循环遍及所有数组的索引返回true,否则返回false。

public boolean linearIn(int[] outer, int[] inner) {
    int i, j;
    // loop over the outer
    for(i = 0, j =0; i < outer.length && j < inner.length; i++) {
       // move to the last same value on the outer
       while(i < outer.length-1 && outer[i] == outer[i+1]) {
           i++;
       }
       // move to the last same value on the inner
       while(j < inner.length-1 && inner[j] == inner[j+1]) {
           j++;
       }
       // immediate false
       if(inner[j] < outer[i]) {
           return false;
       }
       // match - move to the next inner
       if(inner[j] == outer[i]) {
           j++;
       }
    }
    if(j == inner.length) {
        return true;
    }
    return false;
}