java - 搜索算法(优于线性)

标签 java

我必须编写一个方法,如果整数数组中存在三个 3(假设它们不连续),则该方法返回 true。 我在这里编写了这段代码:但是,它返回 true (它不应该这样做)。有人可以指出我的错误吗? arr[]={{4,3,5,2,3,3};

此外,这是一个线性算法。可以做得更好吗?

public static boolean consecutiveThree(int[] arr) {
        int x=0;
        for(int i=0;i<arr.length-1;i++) {

            if((arr[i]!=3 && arr[i+1]==3) || (arr[i]==3 && arr[i+1]!=3)) {
                x++;
                //continue;

            }

            if(x==3)
                return true;

        }
        return false;
    }

最佳答案

你说:

returns true if three 3s are present in an integer array(provided they are not consecutive)

我将其解释为至少有三个 3,并且没有两个 3 是相邻的。

public static boolean hasThreeNonconsecutiveThrees(int... values) {
    int count = 0, streak = 0;
    for (int value : values) {
        if (value != 3)
            streak = 0;
        else if (++streak == 2)
            return false; // Found two consecutive (adjacent) 3s
        else
            count++;
    }
    return (count >= 3);
}

测试

    System.out.println(hasThreeNonconsecutiveThrees(4,3,5,2,3,3)); // false
    System.out.println(hasThreeNonconsecutiveThrees(4,3,5,3,2,3)); // true
    System.out.println(hasThreeNonconsecutiveThrees(1,2,3,4,3));   // false
    System.out.println(hasThreeNonconsecutiveThrees(4,3,5,3,3,3)); // false

输出

false
true
false
false

关于java - 搜索算法(优于线性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51407800/

相关文章:

java - 随机和图形代码太长

java - 我如何每秒将一个数字与一个整数相加

java - Java中的准确计时

java - 将键与值列表进行比较 Java

java - MyBatis 映射器类未在具有两个数据源的 Spring Boot 应用程序中注册

java - Google App Engine 应用程序 (Java) 中的 Facebook 登录

java - NullPointerException 导致 Android 应用程序崩溃

java - 如何利用 AWS 每分钟执行一次方法(多个进程/实例)

带有国际字母的 Java 正则表达式

java - Facebook OAuth redirect_uri 问题