赞
踩
因为数组本身有序,因此最大值只出现在两端,想到左右指针
- class Solution {
- public int[] sortedSquares(int[] nums) {
- int [] res = new int[nums.length];
- int i = 0, j = nums.length-1, k = nums.length-1;
- while (i <= j) {
- if (nums[i] * nums[i] >= nums[j] * nums[j]) {
- res[k--] = nums[i] * nums[i];
- i++;
- } else {
- res[k--] = nums[j] * nums[j];
- j--;
- }
- }
- return res;
- }
- }
使用滑动窗口思想优化,用双指针实现
- class Solution {
- public int minSubArrayLen(int target, int[] nums) {
- int[] sum = new int[nums.length+1];
- for(int i = 1; i <= nums.length; i++) {
- sum[i] = sum[i-1] + nums[i-1];
- }
- int res = 1000000;
- int i = 0;
- for(int j = 1; j <= nums.length; j++) {
-
- while(sum[j]-sum[i] >= target && i <= j) {
- res = res < j-i?res:j-i ;
- i++;
- }
- }
- if (res == 1000000) return 0;
- return res;
- }
- }
就是纯模拟,按照题目描述顺时针遍历
- class Solution {
- public int[][] generateMatrix(int n) {
- int[][] nums = new int[n][n];
- int offset = 1,count = 1, sx = 0, sy = 0;
- int loop = n / 2;
- while (loop-- > 0){
- int i = sy, j = sx;
- for (; j < n-offset; j++) {
- nums[sx][j] = count++;
- }
- for (; i < n-offset; i++) {
- nums[i][j] = count++;
- }
- for (; j > sx; j--) {
- nums[i][j] = count++;
- }
- for (; i > sy; i--) {
- nums[i][j] = count++;
- }
- offset++;
- sx++;
- sy++;
- }
- if (n % 2 == 1) {
- nums[n/2][n/2] = count;
- }
- return nums;
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。