Leetcode 977. Squares of a Sorted Array, Java解法

OCC入门指南:从零开始掌握Open CASCADE Technology 本文是Open CASCADE Technology(OCC)的入门指南,详细介绍了这款开源C++三维几何建模内核的核心概念与价值。内容涵盖从零开始搭建开发环境、编写第一个显示立方体的程序,到深入理解其几何与拓扑核心、掌握Draw测试工具及Handle内存管理等关键编程范式,旨在帮助开发者快速掌握这一工业级CAD/CAE/CAM应用开发利器。 阅读详情

Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.

Example 1:

Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]

Example 2:

Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]

Note:

  1. 1 <= A.length <= 10000
  2. -10000 <= A[i] <= 10000
  3. A is sorted in non-decreasing order.

Approach #1 我的解法 Array.sort() method

class Solution {
    public int[] sortedSquares(int[] A) {
        for(int i=0;i<A.length;i++){
            A[i]*=A[i];
         }
        Arrays.sort(A);
        return A;
    }
}

用Array.sort() method.

Complexity Analysis

  • Time Complexity: O(N log N), where N is the length of A.

  • Space Complexity: O(N). 

Approach #2 Two Pointer

class Solution {
    public int[] sortedSquares(int[] A) {
        int N = A.length;
        int j = 0;
        while (j < N && A[j] < 0)
            j++;
        int i = j-1; //最后一个负数的下标

        int[] ans = new int[N];
        int t = 0;

        while (i >= 0 && j < N) { //从正负数的分界开始,坐标向两边移动
            if (A[i] * A[i] < A[j] * A[j]) {
                ans[t++] = A[i] * A[i];
                i--;
            } else {
                ans[t++] = A[j] * A[j];
                j++;
            }
        }
        
        // 最后加入剩下的
        while (i >= 0) {
            ans[t++] = A[i] * A[i];
            i--;
        }
        while (j < N) {
            ans[t++] = A[j] * A[j];
            j++;
        }

        return ans;
    }
}

 This strategy is to iterate over the negative part in reverse, and the positive part in the forward direction.

We can use two pointers to read the positive and negative parts of the array - one pointer j in the positive direction, and another i in the negative direction.

Now that we are reading two increasing arrays (the squares of the elements), we can merge these arrays together using a two-pointer technique.

Complexity Analysis

  • Time Complexity: O(N), where N is the length of A.

  • Space Complexity: O(N)

【YOLO26实战全攻略】19——智慧交通(一):高速抛洒物与事故检测全流程落地 在智慧交通领域,高速公路抛洒物、交通事故等突发状况常导致二次事故与大规模拥堵,传统人工监控存在响应滞后、覆盖有限等痛点。本文基于Ultralytics YOLO26算法,结合ByteTrack多目标跟踪技术,构建从数据准备、模型训练到边缘部署的全栈式智慧交通检测系统。核心内容包括:多车型专属数据集构建、抛洒物检测模型优化、ByteTrack轨迹跟踪集成、异常事件(违停/逆行/碰撞)识别逻辑实现,以及NVIDIA Jetson边缘设备部署方案。 阅读详情

相关推荐

RK3588嵌入式开发:从零构建Rockit多媒体处理引擎的实战指南

本文详细介绍了如何在RK3588嵌入式平台上从零构建Rockit多媒体处理引擎的实战指南。涵盖开发环境搭建、工具链配置、源码编译流程、硬件加速优化及典型问题解决方案,帮助开发者高效利用RK3588的NPU和VPU加速特性,实现高性能多媒体处理应用。

mango的博客 186

LeetCode 977. Squares of a Sorted Array 有序数组的平方 JAVA实现

题目内容: 给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。   示例 1: 输入:[-4,-1,0,3,10] 输出:[0,1,9,16,100] 示例 2: 输入:[-7,-3,2,3,11] 输出:[4,9,9,49,121]   提示: 1 &lt;= A.length &lt;= 10000 -10000 &lt;= A...

帽帽的博客 776

Zynq 【SDK裸机开发之PS】——DDR的内存分配使用详解

Zynq如果跑操作系统的话,内存管理的工作都会交给系统来操作,但是如果是裸机的话,则需要自己对DDR3的内存进行管理。

shizhibuyi1234的博客 7377

Java/977. Squares of a Sorted Array 有序数组的平方

题目 代码部分(7ms 92.26%) class Solution { public int[] sortedSquares(int[] A) { int len = A.length; int[] res = new int[len]; for(int i = 0; i < l...

qq_38959715的博客 1420

服务器卡死排查实战:从现象分类到根因定位的完整手册

服务器卡死是运维中最令人头疼的故障之一,从游戏圈吐槽的“土豆服务器”到生产环境中的Linux系统无响应、rsync复制挂起,本质都是系统或进程失去正常响应能力。其原理通常涉及CPU、内存、磁盘IO或网络资源耗尽,以及内核和驱动异常。掌握系统化的排查方法,能够帮助工程师快速定位根因、缩短故障时间,避免盲目重启。本文从资源、层级、场景等多维度分类,结合top、dmesg、strace等工具,梳理一套从现象确认、指标收集、日志分析到进程定位的实战排查流程,并覆盖常见高频场景与预防治理建议。无论你是运维新手还是老手

weixin_33851177的博客 374

YOLOv11的QAT(训练感知量化)实战

本文总结了YOLO模型量化感知训练(QAT)的实践要点:QAT通过模拟量化噪声训练模型,比训练后量化(PTQ)更适合密集预测任务。关键实现包括:1)配置对称/非对称量化器;2)排除检测头量化;3)调整学习率策略并添加量化正则;4)选择困难样本校准;5)转换前稳定BN统计量。调试时需检查量化范围、数值分布和逐层突变,并注意SPP等敏感层。建议小模型使用QAT,大模型可能适得其反,且TensorRT的FP16模式可能优于INT8-QAT。量化应以功能正确为前提,避免过度优化。

as1225120794的博客 510

Leetcode 977. Squares of a Sorted Array

Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.   Example 1: Input: [-4,-1,0,3,10] Output: [0,1,9,...

Dive Deep into The Knowledge 716

GPU硬件架构与微架构深度解析34-GPU安全架构深度解析

现代GPU不仅是图形处理器,更是高性能计算平台,安全架构设计至关重要。内存加密- 保护数据在传输和存储时的安全安全启动- 确保固件和软件的完整性隔离机制- 防止不同应用间的数据泄露密钥管理- 安全存储和处理加密密钥。

2301_79143213的博客 99

Median of Two Sorted Array leetcode java

题目:There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).   题解:首先我们先明确什么是median,即中位数。 ...

weixin_34001430的博客 172

PyCharm 接入 OpenAI Codex CLI 的 4 步配置与调试实录

揭示 Codex CLI 在 PyCharm 中上下文失稳的四大根源:CLI 启动模式与 IDE 进程模型冲突、stdin/stdout 流式处理不兼容、环境变量污染、AST 注释缺失,并给出基于 Shell 脚本桥接与结构化上下文注入的稳定接入方案。

weixin_42627902的博客 372

Apollo EM Planner中路径-速度解耦优化的数学建模与仿真分析

摘要 Apollo EM Planner采用路径-速度解耦优化策略解决自动驾驶运动规划问题。该算法将时空轨迹规划分解为路径规划和速度规划两个子问题:首先在静态环境下生成几何最优路径,再优化沿路径的速度曲线。通过五次多项式表示路径和速度,构建包含平滑性、安全性、舒适性的多目标优化函数,并引入弹性模型处理动态障碍物约束。算法具有解耦优化、弹性适应、实时求解等特点,适用于高速公路、城市交叉口等多种场景。数学建模包括路径几何优化、速度动态优化和弹性势能函数,最终生成满足车辆动力学和环境约束的安全轨迹。

走向CTO的路上... 933

977. Squares of a Sorted Array

Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. Example 1: Input: [-4,-1,0,3,10] Output: [0,1,9,16,1...

同销万古愁的博客 452

蓝牙芯片驱动开发-第11章第1题-WiFi蓝牙共存的关键策略有哪些

蓝牙芯片驱动开发-第11章第1题-WiFi蓝牙共存的关键策略有哪些

weixin_42162924的博客 30

Leetcode 977. Squares of a Sorted Array (Java) 错误accept解法,一定要小心

Given an integer arraynumssorted innon-decreasingorder, returnan array ofthe squares of each numbersorted in non-decreasing order. Example 1: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16...

weixin_58080442的博客 125

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

【LeetCode】977. Squares of a Sorted Array

原题网址:https://leetcode.com/problems/squares-of-a-sorted-array/ 解题思路: 我的解:毫无疑问的暴力解。。。。 public int[] sortedSquares(int[] A) { int len = A.length; int[] B = new int[len]; f...

zzf_forgot的博客 199

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

LeetCode C++ 977. Squares of a Sorted Array【Two Pointers】简单

Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. Example 1: Input: [-4,-1,0,3,10] Output: [0,1,9,16,100] Example 2: Input: [-7,-3,2,3,11] Output: [4,9,9,49,121

memcpy0的博客 431

【leetcode】977. Squares of a Sorted Array

思路 从数组左右两边同时开始,因为数组初始有序,所以可以直接比较绝对值大小,大的放在结果数组最后,依次排到最前。 class Solution { public int[] sortedSquares(int[] A) { int[] result = new int[A.length]; for (int i=0,j=A.le...

Art1st_D的博客 203

Java描述 LeetCode,977. Squares of a Sorted Array 有序数组的平方

大家好,我是河海哥,专注于后端,如果可以的话,想做一名code designer而不是普通的coder,一起见证河海哥的成长,您的评论与赞与关注是我的最大动力,如有错误还请不吝赐教,万分感谢。一起支持原创吧!纯手打有笔误还望谅解。 1-1:题目描述 Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasin.

人在江湖 332

leetcode977-Squares of a Sorted Array

这道题目用双指针遍历可以很好的解决,因为平方以后最小的元素肯定是在中间,所以每次只要比较首尾俩个元素的大小取最大值即可。给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。解释:平方后,数组变为 [16,1,0,9,100]输入:nums = [-4,-1,0,3,10]排序后,数组变为 [0,1,9,16,100]输出:[0,1,9,16,100]

我的程序人生 640

LeetCode 977. Squares of a Sorted Array (有序数组的平方)

题目标签:Array   题目给了我们一组 从小到大的 integers,让我们平方数字 并且 也排序成 从小到达。   因为有负数在里面,平方后,负数在array的位置会变动。   可以设left 和 right pointers,从两边遍历,比较一下两个平方后的数字,把大的那个 放入新建的array的末尾。   具体看code。 Java Solution: Runti...

weixin_30344995的博客 112

[leetcode刷题] [Easy] [Array] 977. 有序数组的平方(Squares of a Sorted Array)- Java

题目: Squares of a Sorted Array 英文: Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. Example 1: Input: [-4,-1,0,3,10] Output: [0,1,9,16,100] Example 2: Input: [-

lxfHaHaHa的博客 373

Leetcode 977 Squares of a Sorted Array

class Solution { public int[] sortedSquares(int[] A) { int len=A.length; for(int i=0;i&lt;len;++i){ A[i]=A[i]*A[i]; } Arrays.sort(A); return A;...

Polanwind 162

leetcode刷题记录 easy(8) 977.Squares of a Sorted Array

英文题目: Given an array of integersAsorted in non-decreasing order,return an array of the squares of each number,also in sorted non-decreasing order. Example 1: Input: [-4,-1,0,3,10]Output: [0,1,...

小魑魅的博客 215

Leetcode 977. Squares of a Sorted Array (Java)

我会陆续更新leetcode题目的答案,语言主要选择的是java和python,答案为普通解法,时间和空间复杂度并非最佳,但愿意分享给大家,有更优解朋友,欢迎分享到评论区。谢谢。

weixin_58080442的博客 138

leetcode-day3:Squares of a Sorted Array(有序数组的平方)

数组:有序数组的平方,还有序么? 977. Squares of a Sorted Array LeetCode题目链接 Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. Example 1: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16

丹辰子的博客 1107
上一篇: Leetcode 905. Sort Array By Parity, Java解法
下一篇: Leetcode 561. Array Partition I, Java解法
YuanTheCoder
博客等级 码龄9年 2粉丝 34原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值