当前位置:网站首页>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)。除了存储答案的数组以外,我们只需要维护常量空间。
边栏推荐
猜你喜欢
随机推荐
Image denoising based on edge enhancement Diffusion 】 (cEED) and Coherence Enhancing coursing together (cCED) filter to realize image denoising matlab code
非科班毕业生,五面阿里:四轮技术面 +HR 一面已拿 offer
Use Ehcache distributed cache to easily create commercial-grade high-concurrency, high-performance API interfaces!
在特征通道提升网络性能 --SENet网络详解
Network In Network学习记录
【科研-学习-pytorch】2-线性回归
The Best Open Source Web Application Firewall to Protect Your Web Applications
momerymap mmap 存储映射I/O
makefile file compilation
字节输入流(InputStream)与字节输出流(OutputStream)
2022年中国全民健身发展白皮书
4-4 Matplotlib库 直方图
远程控制项目遇到的bug
Non-major graduates, five-faced Ali: Four rounds of technical + HR have already taken an offer
容器运维平台的故障处理-1
睿智的目标检测61——Tensorflow2 Focal loss详解与在YoloV4当中的实现
模型冻结对应层参数freeze
全文翻译:EDPB 基于设计和默认的数据保护指南
统一身份管理平台IAM单点登录流程及第三方接口设计方案
Sencha Touch延迟加载模块提高程序启动时性能