返回介绍

solution / 1700-1799 / 1708.Largest Subarray Length K / README_EN

发布于 2024-06-17 01:03:15 字数 4136 浏览 0 评论 0 收藏 0

1708. Largest Subarray Length K

中文文档

Description

An array A is larger than some array B if for the first index i where A[i] != B[i], A[i] > B[i].

For example, consider 0-indexing:

  • [1,3,2,4] > [1,2,2,4], since at index 1, 3 > 2.
  • [1,4,4,4] < [2,1,1,1], since at index 0, 1 < 2.

A subarray is a contiguous subsequence of the array.

Given an integer array nums of distinct integers, return the largest subarray of nums of length k.

 

Example 1:

Input: nums = [1,4,5,2,3], k = 3
Output: [5,2,3]
Explanation: The subarrays of size 3 are: [1,4,5], [4,5,2], and [5,2,3].
Of these, [5,2,3] is the largest.

Example 2:

Input: nums = [1,4,5,2,3], k = 4
Output: [4,5,2,3]
Explanation: The subarrays of size 4 are: [1,4,5,2], and [4,5,2,3].
Of these, [4,5,2,3] is the largest.

Example 3:

Input: nums = [1,4,5,2,3], k = 1
Output: [5]

 

Constraints:

  • 1 <= k <= nums.length <= 105
  • 1 <= nums[i] <= 109
  • All the integers of nums are unique.

 

Follow up: What if the integers in nums are not distinct?

Solutions

Solution 1: Simulation

All integers in the array are distinct, so we can first find the index of the maximum element in the range $[0,..n-k]$, and then take $k$ elements starting from this index.

The time complexity is $O(n)$, where $n$ is the length of the array. Ignoring the space consumption of the answer, the space complexity is $O(1)$.

class Solution:
  def largestSubarray(self, nums: List[int], k: int) -> List[int]:
    i = nums.index(max(nums[: len(nums) - k + 1]))
    return nums[i : i + k]
class Solution {
  public int[] largestSubarray(int[] nums, int k) {
    int j = 0;
    for (int i = 1; i < nums.length - k + 1; ++i) {
      if (nums[j] < nums[i]) {
        j = i;
      }
    }
    return Arrays.copyOfRange(nums, j, j + k);
  }
}
class Solution {
public:
  vector<int> largestSubarray(vector<int>& nums, int k) {
    auto i = max_element(nums.begin(), nums.end() - k + 1);
    return {i, i + k};
  }
};
func largestSubarray(nums []int, k int) []int {
  j := 0
  for i := 1; i < len(nums)-k+1; i++ {
    if nums[j] < nums[i] {
      j = i
    }
  }
  return nums[j : j+k]
}
function largestSubarray(nums: number[], k: number): number[] {
  let j = 0;
  for (let i = 1; i < nums.length - k + 1; ++i) {
    if (nums[j] < nums[i]) {
      j = i;
    }
  }
  return nums.slice(j, j + k);
}
impl Solution {
  pub fn largest_subarray(nums: Vec<i32>, k: i32) -> Vec<i32> {
    let mut j = 0;
    for i in 1..=nums.len() - (k as usize) {
      if nums[i] > nums[j] {
        j = i;
      }
    }
    nums[j..j + (k as usize)].to_vec()
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文