检查是否阵是对称的 [英] Checking if array is symmetric

查看:122
本文介绍了检查是否阵是对称的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class symm
{


/* 
 * Returns true if array A is symmetric.
 * Returns false otherwise.
 * n is the number of elements A contains.
 *
 * The running time of your algorithm is O(  ).
 * You may add a brief explanation here if you wish.
 */

 public static boolean symmetric( int[] A, int n )
 {
 return symmHelper(A, n, 0);

 }

private static boolean symmHelper(int[] A, int n, int i) {
if(n==1)
    return true;
if((n==2) && (A[i] == A[n-1-i]))
    return true;
if((i == n-1-i) && (A[i] == A[n-1-i] ))
    return true;    

if(A[i] == A[n-1-i] && i < n/2 )
    return symmHelper(A, n, i+1);

return false;
}  


}  

测试情况:
我通过了所有测试ecxept的fitst上我没有得到任何每当我运行它,我认为这个问题是有在中间的两个2S。我真的不知道有关code,我觉得它可以简化。
是运行时间为O(log n)的?

Test cases: I passed all the tests ecxept the fitst on I get no whenever I run it, I think the problem is that there are two 2s in the middle. And I'm not really sure about the code, I think it can be simplified. Is the running time o(log n)?

5 8 2 2 8 5
YES

5 8 2 2 8 5 YES

10 7 50 16 20 16 50 7 10
YES

10 7 50 16 20 16 50 7 10 YES

5 8 5
YES

5 8 5 YES

1000 1000
YES

1000 1000 YES

6000
YES

6000 YES

10 7 50 16 20 16 50 7 1000
NO

10 7 50 16 20 16 50 7 1000 NO

10 7 50 16 20 16 50 10 700
NO

10 7 50 16 20 16 50 700 10 NO

10 7 50 16 20 16 5000 7 10
NO

10 7 50 16 20 16 5000 7 10 NO

10 7 50 16 20 50 1600 10 7
NO

10 7 50 16 20 1600 50 7 10 NO

10 7 50 16 50 1600 10 7
NO

10 7 50 16 1600 50 7 10 NO

推荐答案

复杂code使得更多的错误。因此,简化它。此外,寻找不平等,而非平等;它更容易检查一个错误比一切是正确的。

Complex code makes for more mistakes. Thus, simplify it. Also, look for inequalities rather than equalities; it's easier to check for one mistake than for everything to be correct.

// A = array, n = size of array, i = looking at now
private static boolean symmHelper(int[] A, int n, int i) {

    if (i > n/2)     // If we're more than halfway without returning false yet, we win
        return true;

    else if (A[i] != A[n-1-i])    // If these two don't match, we lose
        return false;

    else    // If neither of those are the case, try again
        return symmHelper(A, n, i+1);
}

如果我记得我的O()符号的权利,我想这应该是为O(n + 1)。还有其他的东东可以到此去除+1,但它会令code运行速度较慢的整体。

If I remember my O() notation right, I think this should be O(n+1). There are other tweaks you can make to this to remove the +1, but it'll make the code run slower overall.

这篇关于检查是否阵是对称的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆