zoukankan      html  css  js  c++  java
  • 977. 有序数组的平方

    地址:https://leetcode-cn.com/problems/squares-of-a-sorted-array/

    <?php
    /**
     * Created by PhpStorm.
     * User: huahua
     * Date: 2020/10/19
     * Time: 下午4:52
    给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。
    
     
    
    示例 1:
    
    输入:[-4,-1,0,3,10]
    输出:[0,1,9,16,100]
    示例 2:
    
    输入:[-7,-3,2,3,11]
    输出:[4,9,9,49,121]
     
    
    提示:
    
    1 <= A.length <= 10000
    -10000 <= A[i] <= 10000
    A 已按非递减顺序排序。
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/squares-of-a-sorted-array
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
     */
    class Solution {
    
        /**
         * @param Integer[] $A
         * @return Integer[]
         */
        function sortedSquares($A) {
            $res = [];
            $count = count($A);
            $posIndex = 0;
            $negIndex  = 0;
            while($posIndex<$count && $A[$posIndex]<0){
                $posIndex++;
            }
            $negIndex = $posIndex--;
            for($i=0;0<=$posIndex&&$negIndex<$count;$i++){
                $negPow = $A[$negIndex]*$A[$negIndex];
                $posPow  = $A[$posIndex]*$A[$posIndex];
                if($negPow<$posPow){
                    $res[] = $negPow;
                    $negIndex++;
                }else{
                    $res[] = $posPow;
                    $posIndex--;
                }
            }
            while($negIndex<$count){
                $res[] = $A[$negIndex]*$A[$negIndex];
                $negIndex++;
            }
            while($posIndex>=0){
                $res[] = $A[$posIndex]*$A[$posIndex];
                $posIndex--;
            }
            return $res;
        }
    }
  • 相关阅读:
    javascript 中检测数据类型的方法
    javascript 中的类数组和数组
    html5 构造网页的新方式
    关于 jQuery 中的 $.data() 方法和 jQuery 对象上的data 方法
    基于北洋PT站表结构分析以及ORM重写
    面试题准备
    sqlalchemy 外键
    sqlalchemy
    ansible roles
    ansible
  • 原文地址:https://www.cnblogs.com/8013-cmf/p/13841139.html
Copyright © 2011-2022 走看看