每周一道算法题启动
题目
【解法一】合并后排序
排序后的数组自动省略0的数字,又学到了
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
//合并两个数组后排序
for(int i=0; i<n; i++)
{
nums1[m + i] = nums2[i];
}
sort(nums1.begin(), nums1.end());
}
};
【解法二】双指针
时间复杂度:O(m+n)
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
//双指针
int pointer1=0, pointer2=0;
int temporary;
vector<int> num3(m+n); //数组存放
//防止越界
while(pointer1 < m || pointer2 < n)
{
//第一个数组没数放了,第二个数组还有剩的比第一个数组所有数都要大的
//特判情况
if(pointer1 == m)
{
temporary = nums2[pointer2++];
}
else if(pointer2 == n)
{
temporary = nums1[pointer1++];
}
//这里不能等于,要是0的话会放进去,造成不必要麻烦
else if(nums1[pointer1] > nums2[pointer2])
{
temporary = nums2[pointer2++];
}
else
{
temporary = nums1[pointer1++];
}
num3[pointer1 + pointer2 - 1] = temporary;
}
//复制数组回去num1
nums1 = num3;
}
};
执行用时这个不是程序运行时间嗷!
2535. 数组元素和与数字和的绝对差
【参考代码】
class Solution {
public:
int differenceOfSum(vector<int>& nums) {
int sum1 = 0, sum2 = 0;
for(int i=0; i<nums.size(); i++)
{
sum1 += nums[i];
int temp = nums[i];
while(temp)
{
sum2 += temp % 10;
temp /= 10;
}
}
return abs(sum1 - sum2);
}
};
3分03秒搞定
标签:150,temporary,int,pointer2,力扣,pointer1,88,数组,nums1 From: https://blog.csdn.net/CH3CH2CH4/article/details/142484698