代码随想录算法训练营第二天| 977.有序数组的平方 ,209.长度最小的子数组 ,59.螺旋矩阵II

有序数组的平方

题目链接

https://programmercarl.com/0977.%E6%9C%89%E5%BA%8F%E6%95%B0%E7%BB%84%E7%9A%84%E5%B9%B3%E6%96%B9.html

思路

我的想法是双指针,两侧向中间,找最小的元素,但其实是找不到最小的元素,只能找到最大的元素,所以新数组需要倒着填充

    public int[] sortedSquares(int[] nums) {
            int left = 0, right = nums.length - 1, i = nums.length - 1;
            int[] res = new int[nums.length];
            while (left <= right) {
                  if (Math.abs(nums[left]) > Math.abs(nums[right])) {
                       res[i--] = nums[left] * nums[left++];
                  } else {
                      res[i--] = nums[right] * nums[right--];
                  }
           }
           return res;
    }

长度最小的子数组

题目链接

https://programmercarl.com/0209.%E9%95%BF%E5%BA%A6%E6%9C%80%E5%B0%8F%E7%9A%84%E5%AD%90%E6%95%B0%E7%BB%84.html

思路

滑动窗口,因为是全为正数,所以每累加一个元素一定会比之前的和大。
右边界滑动直到和大于给定值,记录长度,然后左边界滑动,继续循环。

      public int minSubArrayLen(int target, int[] nums) {
            int left = 0, right = 0, sum = 0, res = Integer.MAX_VALUE;
            while (right < nums.length) {
                   sum += nums[right++];
                   while (sum >= target) {
                       res = Math.min(res, right - left);
                       sum -= nums[left++];
                   }
                   right++;
           }
           return res;
           // return res == Integer.MAX_VALUE ? 0 : res;
      }

螺旋矩阵

题目链接

https://programmercarl.com/0059.%E8%9E%BA%E6%97%8B%E7%9F%A9%E9%98%B5II.html

思路

循环赋值,找准边界,左开右闭,右边界不做处理。
根据N是奇数还是偶数,需要特殊处理

    public int[][] generateMatrix(int n) {
        int count = 1, l = 0, start = 0, i = 0, j = 0;
        int[][] res = new int[n][n];
        while (l++ < n/2) {
             for (j = start; j < n - l; j++) {
                res[start][j] = count++;
             }
             for (i = start; i < n - l; i++) {
                res[i][j] = count++;
             }
             for (;j >= l; j--) {
              res[i][j] = count++;
             }
             for(;i >= l; i--) {
              res[i][j] = count++;
            }
            start++;
        }
        if (n % 2 == 1) {
            res[start][start] = count++;
        } 
       return res;

    }

自己写的有误,主要是因为每一次循环起始位置没有掌握好,上面那一条数据的横坐标不能用i,因为每循环一次这个值会改变,而i还是初始的值,所以是有问题的。看完卡哥代码,重新理解了下,改了下就好了

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容