刷题日记02 | 977. 有序数组的平方、209.长度最小的子数组、59.螺旋矩阵

100 阅读1分钟

刷题日记02

977. 有序数组的平方

一道比较简单的题,一开始想的是直接平方然后再排序,但题目要求时间复杂度为O(n)。可能还是刷的少了,没有第一时间想到双指针。

class Solution {
    public int[] sortedSquares(int[] nums) {
        int[] result = new int[nums.length];
        int left = 0;
        int right = nums.length - 1;

        for(int i = nums.length - 1; i >=0; i--){
            if(nums[left]*nums[left] > nums[right]* nums[right]){
                result[i] = nums[left]*nums[left];
                left++;
            }else{
                result[i] = nums[right]* nums[right];
                right--;
            }
        }
        return result;
    }
}

209. 长度最小的子数组

二刷的感觉就是有点思路了,知道该用滑动窗口,但对滑动窗口的实现还是不太清楚。比如滑动窗口是两个循环组成的,直觉上感觉不对,时间复杂度不是O(n),但实际上对于n个数据,每个数据最多进行了一次加,一次减,实际上复杂度是O(2n)而不是O(n^2)。

可能再多刷几次,理解滑动窗口的实现方式就好了。

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

59. 螺旋矩阵 II

二刷这道题还是感觉有难度,对于开闭区间的定义已经清楚很多了,问题在于控制螺旋的循环次数,这可能是硬功夫吧,像是n为奇数时,应该对中心的数值特殊处理,这些感觉很难在一时想清楚,还需努力。

class Solution {
    public int[][] generateMatrix(int n) {
        int count = 1;
        int round = 0;
        int start = 0;
        int row = 0;
        int column = 0;
        int[][] result = new int[n][n];
        while(round++ < n / 2){
            for(column = start; column < n - round; column++){
                result[start][column] = count++;
            }
            for(row = start; row < n - round; row++){
                result[row][column] = count++;
            }
            for(; column >= round; column--){
                result[row][column] = count++;
            }
            for(; row >= round; row--){
                result[row][column] = count++;
            }
            start++;

        }
        if(n % 2 == 1){
            result[start][start] = count;
        }
        return result;
    }
}