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);
            }
        }
    }
    
    
  • 相关阅读:
    Java回顾之Spring基础
    Java回顾之ORM框架
    Java回顾之JDBC
    Java回顾之一些基础概念
    Java回顾之反射
    Java回顾之序列化
    platform_device与platform_driver
    DB9 公头母头引脚定义及连接
    浅谈UML的概念和模型之UML九种图
    为Windows 7的winsxs目录瘦身,谨慎。
  • 原文地址:https://www.cnblogs.com/fyusac/p/13829992.html
Copyright © 2011-2022 走看看