zoukankan      html  css  js  c++  java
  • LeetCode-977 Squares of a Sorted Array Solution (with Java)

    1. Description:

    Notes: 

    2. Examples:

    3.Solutions:

     1 /**
     2  * Created by sheepcore on 2019-02-12
     3  */
     4 class Solution {
     5     public int[] sortedSquares(int[] A) {
     6        int length = A.length;
     7         int[] B = new int[length];
     8 
     9         // 原数组全为正数
    10         if (A[0] >= 0) {
    11             for (int i = 0; i < length; i++)
    12                 B[i] = (int) Math.pow(A[i], 2.0);
    13         }
    14 
    15         // 原数组全为负数
    16         else if (A[length - 1] < 0)
    17             for (int i = 0; i < length; i++)
    18                 B[i] = (int) Math.pow(A[length - i - 1], 2);
    19         else {
    20 
    21             int tail = length - 1;
    22             int head = 0, count = 0;
    23             int num;
    24             // 左右摇摆法找最大绝对值数!然后平方装入数组中。
    25             while (head <= tail) {
    26                 num = A[head];
    27                 if (Math.abs(num) > Math.abs(A[tail])) {
    28                     B[length - count - 1] = (int) Math.pow(num, 2);
    29                     head++;
    30 
    31                 } else {
    32                     B[length - count - 1] = (int) Math.pow(A[tail], 2);
    33                     tail--;
    34                 }
    35                 count++;
    36             }
    37         }
    38         return B;
    39     }
    40 }
  • 相关阅读:
    Linux入门
    服务器核心知识
    跨域
    DRF的解析器和渲染器
    DRF的分页
    DRF 权限 频率
    DRF 版本 认证
    Django Rest Framework 视图和路由
    Serializers 序列化组件
    六、Java NIO 通道之间的数据传输
  • 原文地址:https://www.cnblogs.com/sheepcore/p/12395833.html
Copyright © 2011-2022 走看看