当前位置:网站首页>力扣977. 有序数组的平方
力扣977. 有序数组的平方
2022-06-30 04:45:00 【智慧的人不要秃头】
给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。

方法:双指针,分别指向数组的首尾
class Solution {
public:
/*以下方法简单,但是不推荐,时间复杂度是 O(n + nlogn)*/
// vector<int> sortedSquares(vector<int>& nums) {
// for(int i = 0; i < nums.size(); ++i) {
// nums[i] *= nums[i];
// }
// sort(nums.begin(),nums.end()); 快速排序
// return nums;
// }
/*双指针法,由于数组是递增顺序排列的,平方后最大的数一定不是在最左边就是在最右边,不可能在中间
所以我们从两边进行平方比较*/
vector<int> sortedSquares(vector<int>& nums) {
vector<int> result(nums.size(), 0);
int k = nums.size() - 1;
//i指向数组的开始位置,j指向数组的终止位置
for(int i = 0, j = nums.size() - 1; i <= j;) { //i <= j,是为了考虑i和j中间有一个元素的情况
if(nums[i] * nums[i] < nums[j] * nums[j]) {
result[k--] = nums[j] * nums[j];
--j;
}
else{
result[k--] = nums[i] * nums[i];
++i;
}
}
return result;
}
//时间复杂度:O(n)
};边栏推荐
- Input / output and interrupt technology -- microcomputer Chapter 6 learning notes
- Winter vacation parent-child tour, these new york attractions are not only fun but also knowledge
- Array of small C
- Keywords implements and @override
- 力扣292周赛题解
- Thread safety and processing caused by multithreading
- This connection is not a private connection this website may be pretending to steal your personal or financial information
- On mask culling of unity
- 【Paper】2013_ An efficient model predictive control scheme for an unmanned quadrotor helicopter
- BeanFactory创建流程
猜你喜欢

Wildcard SSL certificate issuing time

Qos(Quality of Service)

Winter vacation parent-child tour, these new york attractions are not only fun but also knowledge

This connection is not a private connection this website may be pretending to steal your personal or financial information

EasyRecovery数据恢复软件 恢复了我两年前的照片视频数据

【Paper】2016_ A Learning-Based Fault Tolerant Tracking Control of an Unmanned Quadrotor Helicopter

What to do when the alicloud SSL certificate expires

深度学习------不同方法实现Inception-10

Unity automatic pathfinding

HTC vive cosmos development - handle button event
随机推荐
Introduction to some representations, neighbors and degrees of Graphs
Marvel fan welfare: Singapore Madame Tussauds Wax Museum Marvel 4D experience Museum
Qos(Quality of Service)
Unreal 4 unavigationsystemv1 compilation error
PBR material: basic principle and simple fabrication
Create a simple battle game with photon pun
Implementation of one interview question one distributed lock every day
A must see cruise experience in Bangkok: visit the Mekong River and enjoy the scenery on both sides of the river
Encapsulating JDBC tool classes
Spring Festival Tourism Strategy: welcome the new year in Bangkok, Thailand
IO stream, character read / write, copy
为什么win10开热点后电脑没有网络?
Unity automatic pathfinding
Dual domain SSL certificate
On mask culling of unity
Webots notes day 2
力扣292周赛题解
Error about the new version of UE4: unavigationsystemv1:: simplemovetoactor has been deprecated
[FPGA] IIC读写EEPROM 的实现
Create transfer generation point