• 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);
            }
        }
    }
    
    
  • 相关阅读:
    python环境搭建以及jupyter notebook的安装和启动
    Python base(三)
    Python base(二)
    Python base(一)
    python之装饰器
    python 内置函数 (二)
    函数的简单写法
    python中set的用法
    python在终端运行时增加一些效果
    序列化写到类里
  • 原文地址:https://www.cnblogs.com/fyusac/p/13829992.html
Copyright © 2020-2023  润新知