Day02 数组-双指针+spiralMatrix

  two-point method

 1.4 977. Squares of a Sorted Array
    

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
    two-pointer solution
    the key point of this question is that the square of the elements at both ends of the array will be greater than that in the middle.
        public static int[] sortedSquares(int[] nums) {
            int[] sortSqArr = new int[nums.length];
            int left = 0;
            int right = nums.length-1;
            int pointer = nums.length-1;
            while(left <= right){
                if(nums[left]*nums[left] < nums[right]*nums[right]){
                    sortSqArr[pointer--] = nums[right]*nums[right];
                    right--;
                }else{
                    sortSqArr[pointer--] = nums[left]*nums[left];
                    left++;
                }
            }
            return sortSqArr;
        }
        

sliding window

 1.5 209. Minimum Size Subarray Sum(sliding window)
    

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.
    
    Sliding window, essentially a two-pointer solution, used in solving array or string subsequence problems, such as finding the longest substring without repeating characters, maximum subarray sum,etc.
    the key point of sliding window is to move the start position.
        int start = 0;
        int sum = 0;
        int result = nums.length + 1;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            while(sum >= target){
//                int length =  i - start + 1;
//                result = Math.min(length,result);
                //simplify:
                result = Math.min(i-start+1,result);
                sum -= nums[start];
                start++;
            }
        }
//        if(result == nums.length + 1) return 0;
//        else return result;
        //simplify:
        return result == nums.length + 1 ? 0:result;
    
    

  模拟行为

1.6 59. Spiral Matrix II
    

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

  • 14
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值