【问题标题】:Finding a non-decreasing contiguous subarray找到一个非递减的连续子数组
【发布时间】:2021-05-06 17:58:45
【问题描述】:

考虑一个随机长度和随机正整数值的数组 A[1..n]。我们将 A 的子数组定义为 A 的连续段。我们将从位置 k 到位置 l(都包括在内)的子数组表示为 A[k..l]。如果 A[j] ≤ A[j + 1] 对于 k ≤ j 4,而 A[4..7] = [4; 6; 6; 7] 是数组 A 中最长的上升。该算法不能使用任何辅助存储,例如“额外”数组来执行需要。我不知道如何解决这个问题,这是我最接近解决方案的方法。

class practice {
    public static void ascentLength(int arr[], int size) {
        int length = 0;
        int index = 0;
        for (int i = 0; i < size - 1; i++) {
            index = i;
            if (arr[0] <= arr[i + 1]) {
                System.out.println(arr[i]);
                length++;
            }
            if (arr[0] >= arr[i + 1]) {
                length = 0;
            }
        }
        System.out.println("length: " + length);
    }

    /* Driver program to test above function */
    public static void main(String[] args) {
        int arr[] = {5, 3, 6, 4, 6, 6, 7, 5};
        int n = arr.length;
        ascentLength(arr, n);
    }
}

【问题讨论】:

    标签: java arrays sub-array contiguous


    【解决方案1】:

    您需要使用分离变量跟踪当前上升的大小和最长的上升。在给定的迭代中,您要么开始新的攀登,要么继续现有的攀登。为了简化迭代,我们可以预先处理一些特殊情况(即为空、空或单元素的数组)。

    public int maxAscentLength(int[] arr) {
      if (arr == null || arr.length == 0) {
        return 0;
      }
      if (arr.length == 1) {
        return 1;
      }
      // the largest ascent so far
      int maxLength = 0;
      // length of current ascent - init 1 because 1st element is assumed
      int currLength = 1;
      // start iteration from 1 rather than 0 because 1st element is assumed
      for (int index = 1 ; index < arr.length ; index++) {
        if (arr[index-1] <= arr[index]) {
          // continue ascent
          ++currLength;
        } else {
          // end ascent
          maxLength = Math.max(maxLength, currLength);
          currLength = 1;
        }
      }
      return Math.max(maxLength, currLength);
    }
    

    【讨论】:

      【解决方案2】:

      Tracing 代码和为数组绘制 figures 是了解您的程序在做什么的好方法。

      int arr[] = {5, 3, 6, 4, 6, 6, 7, 5};
      
      int maxLength = 0, count = 0;
      for(int i = 0; i < arr.length - 1; i++){
          if(arr[i + 1] < arr[i]){
              count = 0;
          }else{
              count++;
              if(count > maxLength){
                  maxLength = count;
              }
          }
      }
      System.out.println(maxLength + 1);
      

      最后添加了1,因为我们不能自己给compare一个数字。

      【讨论】:

      • it does not print the array 是什么意思?你想打印具有最长非递减顺序的 arr 子数组吗?但是,对于有效的arr = {4,6,6,7},程序会打印4
      【解决方案3】:

      我马上就注意到了几个错误。

      if 表达式中,您始终将数组的第一个元素与下一个元素进行比较。它应该是数组的当前元素和下一个元素之间的比较。

      count 变量未在任何地方声明。 count 变量的用途是什么?

      在第二个if 块中,在将长度分配为零之前,您不会将长度存储在单独的变量中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-09
        • 1970-01-01
        相关资源
        最近更新 更多