Day02.算法训练

977. 有序数组的平方

class Solution {
    public int[] sortedSquares(int[] nums) {
        int[] newNums = new int[nums.length];
        int i = 0;
        int j = nums.length - 1;
        int newOffset = nums.length - 1;
        while (i <= j) {
            if (nums[i] * nums[i] > nums[j] * nums[j]) {
                newNums[newOffset--] = nums[i] * nums[i];
                i++;
            } else {
                newNums[newOffset--] = nums[j] * nums[j];
                j--;
            }
        }
        return newNums;
    }
}

209. 长度最小的子数组

    public int minSubArrayLen(int target, int[] nums) {
        int result = Integer.MAX_VALUE;
        int i = 0;
        int sum = 0;

        for (int j = 0; j < nums.length; j++) {
            sum = sum + nums[j];
            while (sum >= target) {
                result = Integer.min(result, j - i + 1);
                sum = sum - nums[i];
                i++;
            }
        }
        if (result == Integer.MAX_VALUE) {
            return 0;
        }
        return result;
    }

59. 螺旋矩阵 II

class Solution {
    public int[][] generateMatrix(int n) {

        int startX = 0;
        int startY = 0;
        int count = 1;

        int i = 0;
        int j = 0;

        int[][] result = new int[n][n];
        for (int circle = 0; circle < n / 2; circle++) {

            for (j = startY; j < n - circle - 1; j++) {
                result[startX][j] = count++;
            }

            for (i = startX; i < n - circle - 1; i++) {
                result[i][j] = count++;
            }

            for (; j > startY; j--) {
                result[i][j] = count++;
            }

            for (; i > startX; i--) {
                result[i][j] = count++;
            }

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

你可能感兴趣的:(算法,leetcode,数据结构)