【LeetCode-简单题】977. 有序数组的平方

题目

在这里插入图片描述

方法一:双指针

在这里插入图片描述

class Solution {
    
    
// 方法一 :双指针
    public int[] sortedSquares(int[] nums) {
    
    
      int left = 0;
      int right = nums.length -1 ;
      int[] res = new int[nums.length];//结果集新数组  长度为老数组长度
      for(int i = nums.length-1 ; i>=0 ;i--){
    
    
          int l = nums[left]*nums[left];
          int r = nums[right]*nums[right];
          if( l > r ){
    
    //若左边的值 大于 右边的值 ,让左边的值坐在最后面,然后移动左指针往后
              res[i] = l;
              left++;
          }else {
    
    //若左边的值 <= 右边的值 ,让右边的值坐在当前最后面,然后移动右指针往前
               res[i] = r;
             right--;
          }
      }
      return res;
    }
   
}

方法二:

猜你喜欢

转载自blog.csdn.net/weixin_45618869/article/details/132802432