如果整数在数组中仅存在一次,则返回true的递归方法 [英] Recursive method that returns true if the integer exists only once in an array

查看:52
本文介绍了如果整数在数组中仅存在一次,则返回true的递归方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

int[] arr = {1,2,2,3,4,5};

3 仅在该方法应返回 true 时存在, 2 在该方法应返回 false 时存在两次, 0 不存在,该方法应返回 false .我不断收到运行时错误,该如何解决或该方法有任何方法(仅限递归).这是我的代码:

3 exists only once the method should return true, 2 exists twice the method should return false, 0 doesn't exist the method should return false. I keep getting a runtime error, how do I fix it or is there any way to the method (recursions only). Here is my code:

public static boolean list(int[] a, int num) {
    return helper(a, 0, num);
}

public static boolean helper(int[] a, int i, int num) {
    int count = 0;
    if (a[i] == num)
        count++;
    if (count == 1 && i == a.length)
        return true;
    else if (count != 1 && i == a.length)
        return false;
    else
        return helper(a, i++, num);
}

推荐答案

我运行了您的代码,并得到了

I ran your code and got a java.lang.StackOverflowError. That indicates that your recursive method, named helper keeps calling itself infinitely. It does that because neither of the conditions in the if statements that precede the return statements are ever true.

当以下两个条件之一为真时,您不想递归调用该方法:

You don't want to recursively call the method when one of the following two conditions are true:

  1. 您再次遇到了要在数组中搜索的数字.
  2. 您已经到达数组的末尾.

如果在每次对方法 helper 的调用中将 count 初始化为零,则从不将大于1.因此,应将其设为方法 helper 的参数.

If you keep initializing count to zero in every call to method helper, it will never be greater than one. Hence you should make it a parameter of method helper.

您只需要检查 i 是否等于 a.length ,即可确定您是否已到达数组的末尾.

You just need to check whether i equals a.length to determine whether you have reached the end of the array.

/**
 * Determines whether 'num' occurs exactly once in 'a'.
 *
 * @param a     - array to search
 * @param count - number of occurrences of 'num' in 'a'
 * @param i     - index in 'a'
 * @param num   - number to search for
 *
 * @return 'true' if 'num' occurs exactly once in 'a', otherwise 'false'.
 */
public static boolean helper2(int[] a, int count, int i, int num) {
    if (count > 1) {
        return false;
    }
    if (i == a.length) {
        return count == 1;
    }
    if (a[i] == num) {
        count++;
    }
    return helper2(a, count, i + 1, num);
}

该方法的初始调用是(例如,如果要检查数字 3 在数组中是否仅出现一次.

And the initial call to the method is (for example, if you are checking whether the number 3 appears only once in the array.

int[] a = new int[]{1, 2, 2, 3, 4, 5}; // array of integers to search
int count = 0; // number of occurrences
int index = 0; // index in 'a'
int num = 3; // number to search for
boolean single = helper2(a, count, index, num);

这篇关于如果整数在数组中仅存在一次,则返回true的递归方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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