Skip to content

Commit 6413ca4

Browse files
committed
feat: add squares of a sorted array
1 parent aaa3403 commit 6413ca4

File tree

2 files changed

+97
-0
lines changed

2 files changed

+97
-0
lines changed
62 KB
Binary file not shown.
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
/*
2+
* @Author: Chacha
3+
* @Date: 2022-07-24 22:29:36
4+
* @Last Modified by: Chacha
5+
* @Last Modified time: 2022-07-24 23:08:35
6+
*/
7+
8+
/**
9+
* 来源:https://leetcode.cn/problems/squares-of-a-sorted-array/
10+
*
11+
* 977. 有序数组的平方
12+
*
13+
* 给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。
14+
*
15+
* 示例 1:
16+
* 输入:nums = [-4,-1,0,3,10]
17+
* 输出:[0,1,9,16,100]
18+
* 解释:平方后,数组变为 [16,1,0,9,100],排序后,数组变为 [0,1,9,16,100]
19+
*
20+
* 示例 2:
21+
* 输入:nums = [-7,-3,2,3,11]
22+
* 输出:[4,9,9,49,121]
23+
*
24+
* 提示:
25+
* 1. 1 <= tokens.length <= 10^4
26+
* 2. -10^4 <= nums[i] <= 10^4
27+
* 3. nums 已按 非递减顺序 排序
28+
*
29+
*/
30+
31+
#include <iostream>
32+
#include <vector>
33+
34+
using namespace std;
35+
36+
class Solution
37+
{
38+
private:
39+
/* data */
40+
public:
41+
vector<int> sortSquares(vector<int> &nums);
42+
};
43+
44+
/**
45+
* 方法:双指针法
46+
*
47+
* 数组其实是有序的,只不过负数平方之后可能成为最大数了,那么数组平方的最大值就在数组的两端,不是最左边就是最右边,不可能是中间。
48+
* 此时可以考虑双指针法了,i指向起始位置,j指向终止位置。定义一个新数组result,和A数组一样的大小,让k指向result数组终止位置。
49+
* 如果A[i] * A[i] < A[j] * A[j] 那么result[k--] = A[j] * A[j];
50+
* 如果A[i] * A[i] >= A[j] * A[j] 那么result[k--] = A[i] * A[i];
51+
*
52+
*/
53+
vector<int> Solution::sortSquares(vector<int> &nums)
54+
{
55+
int k = nums.size() - 1;
56+
vector<int> result(nums.size(), 0);
57+
58+
for (int i = 0, j = nums.size() - 1; i <= j;)
59+
{
60+
// 注意这里要i <= j,因为最后要处理两个元素
61+
if (nums[i] * nums[i] < nums[j] * nums[j])
62+
{
63+
result[k--] = nums[j] * nums[j];
64+
j--;
65+
}
66+
else
67+
{
68+
result[k--] = nums[i] * nums[i];
69+
i++;
70+
}
71+
}
72+
73+
return result;
74+
}
75+
76+
void printVector(vector<int> &vec)
77+
{
78+
for (int i = 0; i < vec.size(); i++)
79+
{
80+
printf("%3d ", vec[i]);
81+
}
82+
cout << endl;
83+
}
84+
85+
int main(int argc, char const *argv[])
86+
{
87+
Solution s;
88+
89+
vector<int> nums = {-4, -1, 0, 3, 10};
90+
vector<int> _nums = s.sortSquares(nums);
91+
92+
cout << "nums = [-4, -1, 0, 3, 10], 运算结果为: " << endl;
93+
94+
printVector(_nums);
95+
96+
return 0;
97+
}

0 commit comments

Comments
 (0)