找回密码
 立即注册
首页 业界区 科技 算法day02-数组篇(2)

算法day02-数组篇(2)

育局糊 2025-6-7 18:16:25
目录


  • 209.长度最小的子数组(滑动窗口)

    • 力扣100:无重复字符的最长子串
    • 力扣100:找到字符串中所有字母异位词

  • 59.螺旋矩阵

    • 华为真题螺旋矩阵:
    • 73题矩阵置零:
    • 48题旋转图像:
    • 240题搜索二维矩阵II:

  • 区间和(前缀和):
  • 开发商购买土地(二维前缀和):
 

一、长度最小的子数组

1.png

   力扣209题长度最小的子数组,这一题209. 长度最小的子数组 - 力扣(LeetCode)。主要是考察对滑动窗口的理解。
  1. class Solution {
  2.     public int minSubArrayLen(int target, int[] nums) {
  3.         int left = 0;
  4.         int sum = 0;
  5.         int minLength = Integer.MAX_VALUE;
  6.         for(int right = 0; right < nums.length; right++){
  7.             sum += nums[right];
  8.             while(sum >= target){       //不断缩小窗口但满足条件,直到得到一个最小的值
  9.                 minLength = Math.min(minLength, right - left + 1);
  10.                 sum -= nums[left];
  11.                 left++;
  12.             }
  13.         }
  14.         return minLength == Integer.MAX_VALUE ? 0 : minLength;
  15.     }
  16. }<br>//时间复杂度:O(n),最多执行2n次操作<br>//空间复杂度:O(1),没有额外数组
复制代码
【相关题目】

  • 3题无重复字符的最长子串:https://leetcode.cn/problems/longest-substring-without-repeating-characters/description/?envType=study-plan-v2&envId=top-100-liked
 

  • 438题找到字符串中所有字母异位词:https://leetcode.cn/problems/find-all-anagrams-in-a-string/description/?envType=study-plan-v2&envId=top-100-liked
 
二、螺旋矩阵II

 
2.png

   主要思路:就是定义四个指针,上下左右,重点在判断是否到达边界,然后按照图示的顺序来进行遍历。
[code]class Solution {    public int[][] generateMatrix(int n) {        int left = 0,right = n-1;        int top = 0, bottom = n-1;        int[][] nums = new int[n][n];        int a = 1;        while(left
您需要登录后才可以回帖 登录 | 立即注册