"就算没有看清那株灿烂的花蕊,也应该放声歌颂赞美鲜红的玫瑰"
class Solution {
public:
void moveZeroes(vector& nums) {
for(int cur=0,dest=-1;cur
class Solution {
public:
void duplicateZeros(vector& arr) {
// 1.找到最后一个下标位置
int cur = 0;
int dest = -1;
int n = arr.size();
while(dest < n)
{
if(arr[cur]) dest++;
else dest += 2;
// dest走到边界
if(dest >= n-1) break;
cur++;
}
// 处理边界存在最后一个数为0
if(dest == n)
{
arr[n-1] = 0;
cur--,dest-=2;
}
while(cur >= 0)
{
if(arr[cur]) arr[dest--] = arr[cur--];
else
{
arr[dest--] = 0;
arr[dest--] = 0;
cur--;
}
}
}
};
class Solution {
public:
int bitSum(int n)
{
int sum = 0;
while(n)
{
int a = n % 10;
sum += pow(a,2);
n /= 10;
}
return sum;
}
bool isHappy(int n) {
// 快慢指针
int slow = n,fast = bitSum(n);
while(slow != fast)
{
slow = bitSum(slow);
fast = bitSum(bitSum(fast));
}
return slow == 1 ? true : false;
}
};
class Solution {
public:
int maxArea(vector& arr) {
int n = arr.size();
int left=0,right=n-1;
int ret = 0;
while(left < right)
{
int height = min(arr[right],arr[left]);
int v = (right-left) * height;
ret = max(ret,v);
height == arr[right] ? right--:left++;
}
return ret;
}
};
class Solution {
public:
int triangleNumber(vector& nums) {
int n = nums.size();
sort(nums.begin(),nums.end());
int num = 0;
for(int c=nums.size()-1;c>=2;--c)
{
int left = 0;
int right = c-1;
while(left < right)
{
int sum = nums[left] + nums[right];
if(sum > nums[c])
{
num += (right-left);
right--;
}
else left++;
}
}
return num;
}
};
class Solution {
public:
vector twoSum(vector& nums, int target) {
int n = nums.size();
int left = 0,right=n-1;
while(left < right)
{
int sum = nums[left]+ nums[right];
if(sum > target){
right--;
}
else if(sum < target){
left++;
}
else return {nums[left],nums[right]};
}
return {-1};
}
};
class Solution {
public:
vector> threeSum(vector& nums) {
int n = nums.size();
vector> res;
sort(nums.begin(),nums.end());
for(int i=0;i 0) break;
int left = i+1,right = n-1;
while(left < right)
{
int tar = -nums[i];
int sum = nums[left] + nums[right];
if(sum > tar) right--;
else if(sum < tar) left++;
else
{
res.push_back({nums[i],nums[left],nums[right]});
left++,right--;
// 区间数比较
while(left
这道题的本质和三数之和没什么区别,只不过比三数字和多套一层循环就能够解决了。所以不再细讲,注意到各个循环内的越界去重问题就行。
class Solution {
public:
vector> fourSum(vector& nums, int target) {
int n = nums.size();
// 排序
sort(nums.begin(),nums.end());
vector> res;
for(int i=0;i tar) right--;
else if(sum < tar) left++;
else
{
res.push_back({nums[i],nums[j],nums[left],nums[right]});
left++,right--;
while(left < right && nums[left] == nums[left-1]) left++;
while(left < right && nums[right] == nums[right+1]) right--;
}
}
j++;
while(j < n && nums[j] == nums[j-1]) j++;
}
i++;
while(i < n && nums[i] == nums[i-1]) i++;
}
return res;
}
};
本篇到此结束,感谢你的阅读。
祝你好运,向阳而生~