首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >数组是否为双侧数组

数组是否为双侧数组
EN

Code Review用户
提问于 2016-01-21 04:13:16
回答 1查看 435关注 0票数 6

另一个twinoid被定义为一个数组,该数组恰好有两个相邻的偶数值。例如,{3, 3, 2, 6, 7}是一个孪生数组,因为它恰好有两个偶数(2和6),并且它们彼此相邻。下面的数组不是孪生数组。

  • {3, 3, 2, 6, 6, 7},因为它有three even值。
  • {3, 3, 2, 7, 6, 7},因为偶数值是彼此之间的not adjacent
  • {3, 8, 5, 7, 3},因为它具有only one even值。

我编写Twinoid是为了检查给定的数组是否为twinoid

代码语言:javascript
复制
public class Twinoid {

public static void main(String args[]) {
    System.out.println("The result is: " + isTwinoid(new int[]{3, 3, 2, 6, 7}));
}

public static boolean isTwinoid(int[] a) {
    boolean status = false;
    int i;
    int count = 0;
    for (i = 0; i < a.length; i++) {
        if (a[i] % 2 == 0) {
            count++;
        }
    }
    if (count == 2) {
        int j;
        for (j = 0; j < a.length; j++) {
            if (a[j] % 2 == 0) {
                System.out.println(a[j]);
                break;
            }
        }
        int nextValue = a[j + 1];
        System.out.println(nextValue);
        if (nextValue % 2 == 0) {
            status = true;
        }
    } else {
        status = false;
    }
    return status;
}
}
EN

回答 1

Code Review用户

发布于 2021-08-13 09:23:57

正如mdfst13所指出的,您不需要扫描数组两次。

实际上,您可能只需要在第一个偶数之后检查下一个int,因为如果它不是偶数,就可以停止。

否则,继续扫描数组的其余部分,如果找到第三个偶数,则可以停止。

代码语言:javascript
复制
public class Twinoid {

    /**
     * Returns true if the array contains exactly two even values that are adjacent.
     */
    public static boolean isTwinoid(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            if (!isEven(array[i])) {
                continue;
            }
            if (!isEven(array[i + 1])) {
                return false;
            }
            return !containsEvenFromIndex(array, i + 2);
        }
        return false;
    }

    private static boolean containsEvenFromIndex(int[] array, int i) {
        while (i < array.length) {
            if (isEven(array[i])) {
                return true;
            }
            i++;
        }
        return false;
    }

    private static boolean isEven(int n) {
        return n % 2 == 0;
    }

}
票数 0
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/117450

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档