第一章 数组part02

89 阅读2分钟

977. Squares of a Sorted Array

leetcode.com/problems/sq…

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

题目解析:

  • 暴力解法为先求出所有元素的平方值再排序,时间复杂度为O(nlogn)
  • 使用双指针的时间复杂度为O(n)

代码

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

209. Minimum Size Subarray Sum

leetcode.com/problems/mi…

Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.

题目解析:

  • 暴力求解需要用双层循环,时间复杂度为O(n2n^2)
  • 求数组区间的和问题,可以使用双指针解决,时间复杂度为O(n)

代码:

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int left = 0, sum = 0;
        int minLength = nums.length + 1;
        for (int right = 0; right < nums.length; right++) {
            sum += nums[right];
            while(sum >= target) {
                int tempLen = right - left + 1;
                minLength = tempLen < minLength ? tempLen : minLength;
                sum -= nums[left++];
            }
        }
        return minLength != nums.length + 1 ? minLength : 0;
    }
}

59. Spiral Matrix II

leetcode.com/problems/sp…

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.

Example 1:

题目解析:

  • 本题为二维数组上模拟
  • 可以通过判断下一步所在的位置的值是否等于0判断是否需要改变方向
  • Math.floorMod(a, b) = (a % b + b) % b 可以处理值为负数的情况

代码:

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int d = 0;
        int i = 1;
        int row = 0, col = 0;
        while (i <= n * n) {
            matrix[row][col] = i++;
            int nextRow = Math.floorMod(row + directions[d][0], n);
            int nextCol = Math.floorMod(col + directions[d][1], n);
            if (matrix[nextRow][nextCol] != 0) {
                d = (d + 1) % 4;
            }
            row += directions[d][0];
            col += directions[d][1];
        }
        return matrix;
    }
}

总结

数组问题的思路:

  • 二分法:排序数组,时间复杂度O(logn)
  • 双指针法:快慢指针,时间复杂度O(n)
  • 滑动窗口:区间求和,时间复杂度O(n)
  • 模拟行为:二维数组