leetcode 977.有序数组的平方
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {//肯定是循环的时候数组越界了
int left = 0;
int right = 0;
int n = nums.size();
while (left < n) {//找到第一个非负数
if (nums[left] < 0) {
++left;
}else {
right = left;
left = right - 1;
break;
}
}
vector<int> ans;
while (left >= 0 || right < n) {
int leftSquare = nums[left] * nums[left];
int rightSquare = nums[right] * nums[right];
if (left < 0) {//没有负数,right = 0;
ans.push_back(rightSquare);
++right;
}else if (right == n) {//没有正数,right = n;
ans.push_back(leftSquare);
--left;
}else if (leftSquare < rightSquare) {
ans.push_back(leftSquare);
--left;
}else {
ans.push_back(rightSquare);
++right;
}
}
return ans;
}
};
最好是加一个条件,
if(left<=right){
}
这样就不会越界了。
left有可能>n的
您的问题已经有小伙伴解答了,请点击【采纳】按钮,采纳帮您提供解决思路的答案,给回答的人一些鼓励哦~~
ps:开通问答VIP,享受5次/月 有问必答服务,了解详情↓↓↓
【电脑端】戳>>> https://vip.csdn.net/askvip?utm_source=1146287632
【APP 】 戳>>> https://mall.csdn.net/item/52471?utm_source=1146287632