【问题标题】:Max length increasing super array made by joining two increasing subarray连接两个递增子数组的最大长度递增超级数组
【发布时间】:2020-04-22 19:34:09
【问题描述】:

问题: 给定一个数组,找到两个递增的子数组(比如ab),这样当它们加入时会产生一个递增的数组(比如ab)。我们需要找到数组ab的最大可能长度。

例如: 给定array = [2 3 1 2 5 4 5]

两个子数组是a = [2 3]b = [4, 5]ab = [2 3 4 5] 输出:length(ab) = 4

【问题讨论】:

  • 有趣。每个增加的子数组对我来说都像是一个有开始和结束的区间。
  • 另请注意,递增子数组内部也有多个递增子数组。所以类似于订单统计树的东西应该会有所帮助。

标签: arrays algorithm data-structures time-complexity


【解决方案1】:

我会用蛮力解决它。通过蛮力,我可以获得所有子数组,然后检查它是否在增加。然后我可以使用合并数组并检查是否有重叠元素。如果有重叠元素将删除它们并存储长度。

获取所有子数组的时间复杂度将是O(n^2)(我假设子数组将保持相对顺序,而不是指所有子集)。然后将使用队列对子数组进行排序,排序策略将是根据第一个元素。然后我会检查有多少可以与增加的属性合并(你用来合并已经排序的数组的东西)。

然后统计合并后严格递增的数组。

其他两种方法可以通过动态规划使用(这与最长连续递增子数组相同):(Look here

第一种方法:

 public int lengthOfLIS(int[] nums) {            
    if(nums.length == 0) { return 0; }

    int[] dp = new int[nums.length];

    int len = 0;

    for(int n: nums) {

        // Find the position of it in binary tree.
        int pos = Arrays.binarySearch(dp, 0, len, n);

        // Convert the negative position to positive.
        if(pos < 0) { pos = -1*(pos + 1); }

        // assign the value to n
        dp[pos] = n;

        // If the length of the dp grows and becomes equal to the current len
        // assign the output length to that.
        if(pos == len) {
           len++;
        }
    }

    // Return the length.
    return len;
}

另一种方法:

public int lengthOfLIS(int[] nums) {

    if(nums == null || nums.length == 0) { return 0; }
    int n = nums.length;

    Integer lis[] = new Integer[n]; 
    int max = 0; 

    /* Initialize LIS values for all indexes 
    for ( int i = 0; i < n; i++ ) {
        lis[i] = 1; 
    }

    /* Compute optimized LIS values in bottom up manner 
    for (int i = 1; i < n; i++ ) {
        for ( int j = 0; j < i; j++ )  {
            if ( nums[i] > nums[j] && lis[i] < lis[j] + 1) {
                lis[i] = lis[j] + 1; 
            }
        } 
    }
    max = Collections.max(Arrays.asList(lis));
    return max; 
}

【讨论】:

  • 如何查看“增加属性可以合并多少个”?如果你只是蛮力的话,有 n^4 对。
【解决方案2】:

想法是蛮力的,通过蛮力我可以得到所有增加的子数组。然后我可以使用检查是否有重叠元素。如果有重叠元素会计算合并后的长度,然后比较并存储最大长度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多