当前位置:网站首页>做题笔记5(有序数组的平方)
做题笔记5(有序数组的平方)
2022-07-28 16:02:00 【竹林观月】
题目
一.代码
1)使用冒泡排序,会超出时间限制。
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int n = nums.size();
vector<int> newnums(n, 0);
for (int i = 0; i < n; i++)
{
newnums[i] = nums[i] * nums[i];
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
int temp;
if (newnums[j] > newnums[j + 1])
{
temp = newnums[j + 1];
newnums[j + 1] = newnums[j];
newnums[j] = temp;
}
}
}
return newnums;
}
};
2)使用sort函数
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int n = nums.size();
vector<int> newnums(n, 0);
for (int i = 0; i < n; i++)
{
newnums[i] = nums[i] * nums[i];
}
sort(newnums.begin(),newnums.end());
return newnums;
}
};
3)双指针法
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int n = nums.size();
vector<int>ans(n);
for (int i = 0, j = n - 1, pos = n - 1; i <= j; pos--)
{
if (nums[i] * nums[i] >= nums[j] * nums[j])
{
ans[pos] = nums[i] * nums[i];
i++;
}
else
{
ans[pos] = nums[j] * nums[j];
j--;
}
}
return ans;
}
};
二.sort函数
1.复杂度为n*log2(n);
2.包含在头文件algorithm下;
3.用两个参数时,默认为升序排序;
4.用三个参数时
bool compare(int a, int b)
{
return a < b;
}
sort(t.begin(), t.end(), compare);
可决定升序或是降序。
边栏推荐
- About mit6.828_ HW9_ Some problems of barriers xv6 homework9
- MySQL CDC if the binlog log file is incomplete, can you read all the data in the full volume stage
- [learn slam from scratch] publish the coordinate system transformation relationship to topic TF
- 局域网无法访问apache服务器
- Call DLL file without source code
- 【深度学习】:《PyTorch入门到项目实战》:简洁代码实现线性神经网络(附代码)
- LeetCode每日一练 —— 剑指Offer 56 数组中数字出现的次数
- Tcp/ip related
- 排序1-插入排序与希尔排序
- 我该如何理解工艺
猜你喜欢

USB产品(FX3、CCG3PA)的调试方法

关于 CMS 垃圾回收器,你真的懂了吗?

LeetCode每日一练 —— 160. 相交链表

Applet: get element node information

TCP handshake, waving, time wait connection reset and other records

IM即时通讯软件开发网络请求成功率的优化

排序3-选择排序与归并排序(递归实现+非递归实现)

Learn ABAQUS script programming script in an hour

Interesting kotlin 0x07:composition

Ruoyi集成flyway后启动报错的解决方法
随机推荐
有趣的 Kotlin 0x0A:Fun with composition
Leetcode learn complex questions with random pointer linked lists (detailed explanation)
Li Hongyi, machine learning 5. Tips for neural network design
小程序:scroll-view默认滑倒最下面
What does it remote operation and maintenance mean? Which is the best remote operation and maintenance software?
NoSQL introduction practice notes I
【深度学习】:《PyTorch入门到项目实战》第六天:多层感知机(含代码)
Using pyqt to design gui in ABAQUS
Interesting kotlin 0x08:what am I
Interesting kotlin 0x09:extensions are resolved statically
智慧园区是未来发展的趋势吗?
大学生参加六星教育PHP培训,找到了薪水远超同龄人的工作
小程序:获取元素节点信息
College students participated in six Star Education PHP training and found jobs with salaries far higher than those of their peers
WSL+Valgrind+Clion
El input limit can only input the specified number
First day of QT study
微软:Edge 浏览器已内置磁盘缓存压缩技术,可节省空间占用且不降低系统性能
13 differences between MySQL and Oracle
LeetCode-学会复杂带随机指针链表的题(详解)