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

    package com.example.lettcode.dailyexercises;
    
    /**
     * @Class SortedSquares
     * @Description 977 有序数组的平方
     * @Author
     * @Date 2020/10/16
     **/
    public class SortedSquares {
        public static int[] sortedSquares(int[] A) {
            if (A.length == 0) return new int[]{};
            int indexZero = 0;
            // 需要考虑下标是否越界
            while (indexZero < A.length && A[indexZero] < 0) {
                ++indexZero;
            }
            int[] res = new int[A.length];
            int index = -1;
            int indexL = indexZero - 1;
            int indexR = indexZero;
            while (indexL >= 0 && indexR < A.length) {
                if (Math.abs(A[indexL]) < Math.abs(A[indexR])) {
                    res[++index] = A[indexL] * A[indexL];
                    indexL--;
                } else {
                    res[++index] = A[indexR] * A[indexR];
                    indexR++;
                }
            }
    
            while (indexL >= 0) {
                res[++index] = A[indexL] * A[indexL];
                indexL--;
            }
            while (indexR < A.length) {
                res[++index] = A[indexR] * A[indexR];
                indexR++;
            }
            return res;
        }
    
    
        public static void main(String[] args) {
            int[] A = new int[]{-7, -3, 2, 3, 11};
            int[] ans = sortedSquares(A);
            System.out.println("SortedSquares demo01 result:");
            for (int num : ans) {
                System.out.print("," + num);
            }
            System.out.println();
            A = new int[]{-4, -1, 0, 3, 10};
            ans = sortedSquares(A);
            System.out.println("SortedSquares demo02 result:");
            for (int num : ans) {
                System.out.print("," + num);
            }
            System.out.println();
            A = new int[]{-1};
            ans = sortedSquares(A);
            System.out.println("SortedSquares demo03 result:");
            for (int num : ans) {
                System.out.print("," + num);
            }
        }
    }
    
    
  • 相关阅读:
    Mysql权限控制
    Linux查看端口
    linus 下redis守护进程启动
    pymongo创建索引
    mongo批量操作存在更新否则插入
    梯度下降推导过程资料整理
    [转]mitmproxy套件使用攻略及定制化开发
    终极利器!利用appium和mitmproxy登录获取cookies
    how-to-pass-a-class-variable-to-a-decorator-inside-class-definition
    python进阶之魔法函数
  • 原文地址:https://www.cnblogs.com/fyusac/p/13829992.html
Copyright © 2011-2022 走看看