当前位置:网站首页>(oj)原地移除数组中所有的元素val、删除排序数组中的重复项、合并两个有序数组
(oj)原地移除数组中所有的元素val、删除排序数组中的重复项、合并两个有序数组
2022-08-05 05:17:00 【Captain林】
本篇文章计划用简单的代码方式向大家介绍题目所述的三个oj题的解题方法
目录
1. 原地移除数组中所有的元素val
题目如下


解法如下

int removeElement(int* nums, int numsSize, int val)
{
int left = 0;
for(int right=0; right<numsSize; right++)
{
if(nums[right] != val)//要改变数组
{
nums[left] = nums[right];
left++;
}
}
return left;
}2. 删除排序数组中的重复项
题目如下


解法如下

int removeDuplicates(int* nums, int numsSize){
int src = 1;
int dst = 0;
while(src < numsSize)
{
if(nums[src] == nums[dst])
{
src++;
}
else
{
dst++;
nums[dst] = nums[src];
src++;
}
}
return dst+1;
}3.合并两个有序数组
题目如下

解法如下
设end、end1、end2,当end1指向的值大于end2,先将end1的值放到end所在位置,反之亦然
注意:有可能会出现end1遍历完而end2没有遍历完的情况,这时可以额外增加一个循环使数组nums2的所有值复制到数组nums1上

void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n)
{
int end1 = m-1;
int end2 = n-1;
int end = m+n-1;
while(end1 >= 0 && end2 >= 0)
{
if(nums1[end1] > nums2[end2])
{
nums1[end--] = nums1[end1--];
}
else
{
nums1[end--] = nums2[end2--];
}
}
while(end2 >= 0)
{
nums1[end--] = nums2[end2--];
}
}4.结语
看到这里,相信老铁们对如何解决上述oj题有了相应的了解。
我是计算机海洋的新进船长Captain_ldx,如果我的文章能对您有帮助的话,麻烦各位观众姥爷们点赞、收藏、关注,你们的每一次举手之劳都将化为船长的前进动力!
边栏推荐
- 【论文精读】R-CNN 之预测框回归(Bounding box regression)问题详述
- leetCode刷题之第31题
- 网络信息安全运营方法论 (上)
- 九、响应处理——内容协商底层原理
- 【22李宏毅机器学习】课程大纲概述
- TinyFlashDB:一种超轻量的可纠错的通用单片机flash存储方案
- [Pytorch study notes] 9. How to evaluate the classification results of the classifier - using confusion matrix, F1-score, ROC curve, PR curve, etc. (taking Softmax binary classification as an example)
- 【ts】typescript高阶:映射类型与keyof
- [Pytorch study notes] 11. Take a subset of the Dataset and shuffle the order of the Dataset (using Subset, random_split)
- Tensorflow踩坑笔记,记录各种报错和解决方法
猜你喜欢

【Pytorch学习笔记】11.取Dataset的子集、给Dataset打乱顺序的方法(使用Subset、random_split)

LeetCode刷题之第129题

物联网-广域网技术之NB-IoT

网工必用神器:网络排查工具MTR

基于STM32F407的一个温度传感器报警系统(用的是DS18B20温度传感器,4针0.96寸OLED显示屏,并且附带日期显示)

【数据库和SQL学习笔记】6.SELECT查询4:嵌套查询、对查询结果进行操作

WCH系列芯片CoreMark跑分

SQL (2) - join window function view

CVPR2021 - Inception Convolution with Efficient Dilation Search

CAN、CAN FD
随机推荐
MySQL
ECCV2022 | RU&谷歌提出用CLIP进行zero-shot目标检测!
【ts】typeScript高阶:any和unknown
SharedPreferences and SQlite database
【数据库和SQL学习笔记】9.(T-SQL语言)定义变量、高级查询、流程控制(条件、循环等)
LeetCode刷题之第86题
LeetCode刷题之第54题
Machine Learning (1) - Machine Learning Fundamentals
原来何恺明提出的MAE还是一种数据增强
MaskDistill-不需要标注数据的语义分割
You should write like this
Service
基于STM32F407的WIFI通信(使用的是ESP8266模块)
LeetCode刷题之第129题
tensorflow的session和内存溢出
【Pytorch学习笔记】11.取Dataset的子集、给Dataset打乱顺序的方法(使用Subset、random_split)
SharedPreferences和SQlite数据库
C语言联合体union占用空间大小问题
IT系统运行维护方法及策略
[Pytorch study notes] 9. How to evaluate the classification results of the classifier - using confusion matrix, F1-score, ROC curve, PR curve, etc. (taking Softmax binary classification as an example)