【问题标题】:recursively finding two elements with the smallest difference in an array递归查找数组中差异最小的两个元素
【发布时间】:2016-03-16 21:42:14
【问题描述】:

我正在尝试递归地在数组中找到两个差异最小的元素(假设数组已经按升序排序)。

我一直试图让我的代码只返回最小的和,但递归似乎无法正常工作。

public class SmallestDiff {
    public static void main (String [] args){
        int [] x = {1,3,6,9,126};
        System.out.println(smallestDiff(x,4));
    }

    public static int smallestDiff (int [] array, int index){
        int result;
        if (index>0){
            int diff = Math.abs((array[index]-array[index-1]));
            result = Math.min (diff, smallestDiff(array,index-1));
        }
        else {
            return array[0];
        }
        return result;
    }
}

【问题讨论】:

  • 我认为这应该是对递归技术的培训。在实践中,您的任务应该通过迭代来解决。

标签: java arrays algorithm recursion difference


【解决方案1】:

你的错误是

return array[0];

array[0] 不是值之间的差异,因此不应返回。修复程序的最简单方法是将这一行替换为

return array[1] - array[0];

【讨论】:

    【解决方案2】:

    试试这个:

    公共类 SmallestDiff {

    public static void main(String[] args) {
        int[] x = { 1, 3, 6, 9, 126 };
    
        int result;
        if (x.length < 2) {
            result = x[0];
        }
        else{
            result = smallestDiff(x, x.length-1);
        }
        System.out.println(result);
    
    }
    
    public static int smallestDiff(int[] array, int index) {
    
        if (index == 0) {
            return Integer.MAX_VALUE;
    
        }
    
        int diff = (array[index] - array[index - 1]);
        return Math.min(diff, smallestDiff(array, index - 1));
    
    }
    

    }

    如果数组中只有一个元素,此解决方案会打印第一个元素。否则,它总是会导致两个元素之间的最小差异。

    【讨论】:

      【解决方案3】:

      如果您的数组已排序,则无需递归。 下面的代码解决了迭代的问题。

      public class SmallestDiff {
      
      public static void main(String[] args) {
          int[] x = {1, 3, 6, 9, 126};
          System.out.println(smallestDiff(x));
      }
      
      public static int smallestDiff(int[] array) {
          int result = Integer.MAX_VALUE;
          for (int i = 0; i < array.length - 1; i++) {
              int diff = Math.abs((array[i] - array[i + 1]));
              if (diff < result) {
                  result = diff;
              }
          }
          return result;
      }
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-17
        • 1970-01-01
        • 2013-04-28
        • 2012-03-16
        • 2016-07-05
        • 2016-03-27
        • 1970-01-01
        相关资源
        最近更新 更多