【问题标题】:recursive exercise on codingbat关于codingbat的递归练习
【发布时间】:2016-10-30 18:19:07
【问题描述】:

我目前正在codingbat 网站上做一个练习,上面写着:

给定一个整数数组,如果数组包含 6,则递归计算。 我们将使用只考虑数组的一部分的约定 从给定索引开始。这样一个递归调用就可以通过 index+1 向下移动数组。初始调用将传入索引为 0.

示例:

array6([1, 6, 4], 0) → true

array6([1, 4], 0) → false

array6([6], 0) → true

我的解决方案如下,但由于某种原因,当我的if(nums[index] == 6) 为真时,它仍会执行else block. 中的代码

我的问题:

从技术上讲,当if statement 中的代码被执行时,它不应该执行else block 中的代码。那为什么会持续存在呢?;

public static boolean array6(int[] nums, int index) { 

    if(nums.length == 0){
          return false;
    }

    if(index == nums.length-1 && nums[index] != 6){
          return false;
    }

    if(index == nums.length-1 && nums[index] == 6){
          return true;
    }

    if(nums[index] == 6){
           return true;

    }else{
           array6(nums,index+1);
    }

    return false;
}

【问题讨论】:

    标签: java arrays recursion


    【解决方案1】:

    通过递归返回您收到的值。改变

    array6(nums,index+1);
    

    类似

    return array6(nums,index+1);
    

    【讨论】:

      【解决方案2】:
      public static boolean find(int[] a, int value) {
          if (a == null) {
              throw new IllegalArgumentException("Illegal argument!");
          }
          return find(a, value, 0);
      }
      
      private static boolean find(int[] a, int value, int index) {
          if (index == a.length) return false;
          if (a[index] == value) return true;
          return find(a, value, index + 1);
      }
      

      【讨论】:

        【解决方案3】:

        检查我的回答是否满足你的问题

        public boolean array6(int[] nums, int index) {
          if(nums.length == 0 || index > nums.length-1){
            return false;
          }
          if(nums[index] == 6){
            return true;
          }
        
          return array6(nums,index+1);
        }
        

        【讨论】:

          猜你喜欢
          • 2015-03-01
          • 2014-03-14
          • 1970-01-01
          • 2013-12-16
          • 1970-01-01
          • 2023-03-21
          • 1970-01-01
          • 1970-01-01
          • 2012-07-02
          相关资源
          最近更新 更多