当前位置:网站首页>LeetCode每日两题01:有序数组的平方 (均1200道)方法:双指针
LeetCode每日两题01:有序数组的平方 (均1200道)方法:双指针
2022-08-09 01:13:00 【那人独钓寒江雪.】
解题思路:最简单的方法就是将数组 nums 中的数平方后直接排序然后放在另一个新建的数组中。
class Solution {
public int[] sortedSquares(int[] nums) {
int[] ans=new int[nums.length];
for (int i=0;i<nums.length;i++){
ans[i]=nums[i]*nums[i];
}
Arrays.sort(ans);
return ans;
}
}
class Solution {
public int[] sortedSquares(int[] nums) {
int n = nums.length;
int negative = -1;
for (int i = 0; i < n; ++i) {
if (nums[i] < 0) {
negative = i;
} else {
break;
}
}
int[] ans = new int[n];
int index = 0, i = negative, j = negative + 1;
while (i >= 0 || j < n) {
if (i < 0) {
ans[index] = nums[j] * nums[j];
++j;
} else if (j == n) {
ans[index] = nums[i] * nums[i];
--i;
} else if (nums[i] * nums[i] < nums[j] * nums[j]) {
ans[index] = nums[i] * nums[i];
--i;
} else {
ans[index] = nums[j] * nums[j];
++j;
}
++index;
}
return ans;
}
}
复杂度分析
时间复杂度:O(n)O(n),其中 nn 是数组 \textit{
nums}nums 的长度。
空间复杂度:O(1)O(1)。除了存储答案的数组以外,我们只需要维护常量空间。
边栏推荐
猜你喜欢
随机推荐
微信企业号开发之接收响应消息
【图像去噪】基于边缘增强扩散 (cEED) 和 Coherence Enhancing Diffusion (cCED) 滤波器实现图像去噪附matlab代码
OIDC 思维导图
torch.utils.data.DataLoader
A double non-programmer interviewed Ant, Meituan, Ctrip and other big companies with offers to share the interview process
全新Swagger3.0教程,OAS3快速配置指南,实现API接口文档自动化!
经典卷积神经网络ZFNet--解卷积可视化
ONNX是什么?怎么用?[简明解读版]
易周金融分析 | 互联网系小贷平台密集增资;上半年银行理财子公司综合评价指数发布
STM32H750VBT6 Keil5 error :flash download failed cortex-M7
在vscode中编辑、编译、下载Keil工程
统一身份管理平台IAM单点登录流程及第三方接口设计方案
Oracle最后一个商用免费版本JDK1.8.202
理财产品募集期和开放期有什么区别?
【科研-学习-pytorch】3-分类问题
C语言-大端存储和小端存储
全文翻译:欧盟第29条数据保护工作组 数据保护官指南
Pinctrl 子系统简介
任务五 处理连续型数据
RS&FSW测试脚本