领扣LintCode算法问题答案-1517. 最大子数组

    科技2022-07-13  119

    领扣LintCode算法问题答案-1517. 最大子数组

    目录

    1517. 最大子数组描述样例 1:样例 2: 题解鸣谢

    1517. 最大子数组

    描述

    给定一个由N个整数构成的数组A和一个整数K, 从所有长度为K的A的连续子数组中返回最大的连续子数组。 如果两个数组中的第一个不相等元素在A中的值大于B中的值,则我们定义子数组A大于子数组B。 例如,A=[1,2,4,3],B=[1,2,3,5]. A大于B,因为A [2]> B [2]。

    1 <= K <= N <= 1001 <= A[i] <= 1000

    样例 1:

    输入: [1,4,3,2,5] 4 输出: [4,3,2,5] 解释: 该数组有两个长度为4的连续子数组,分别为: [1,4,3,2] 以及 [4,3,2,5]. 所以最大的子数组为 [4,3,2,5].

    样例 2:

    输入: [7,1,2,7,9,2,3,1,2,5] 4 输出: [9,2,3,1]

    题解

    public class Solution { /** * @param A: the array * @param K: the length * @return: the largest subarray */ public int[] largestSubarray(int[] A, int K) { // Write your code here. if (K >= A.length) { return A; } int maxIndex = 0; for (int i = 1; i <= A.length - K; i++) { if (A[i] > A[maxIndex]) { maxIndex = i; } else if (A[i] == A[maxIndex]) { for (int j = 1; j < K; j++) { if (A[i + j] < A[maxIndex + j]) { break; } if (A[i + j] > A[maxIndex + j]) { maxIndex = i; break; } } } } int[] ret = new int[K]; System.arraycopy(A, maxIndex, ret, 0, K); return ret; } }

    原题链接点这里

    鸣谢

    非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。 欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。

    Processed: 0.012, SQL: 8