顺序表例题
example-1
题目链接:https://leetcode.cn/problems/remove-element/description/
解题思路动画:
代码如下:
int removeElement(int* nums, int numsSize, int val)
{
//方法1:新的数组的元素比较少,可以覆盖在原来的数组上 新指针 旧指针
int left=0;
for(int right=0;right<numsSize;right++)
{
if(nums[right]!=val)
{
nums[left]=nums[right];
left++;
}
}
return left;
}
example-2
题目链接:https://leetcode.cn/problems/remove-duplicates-from-sorted-array/
解题思路动画:
代码如下:
int removeDuplicates(int* nums, int numsSize)
{
//有序的数组中重复的数值都是挨着的
int slow=1;
//新的数组中一定有一个数在(第一个数字不用比较),这个数作为原始数据和后面的部分对比
for(int fast=1;fast<numsSize;fast++)
{
if(nums[fast]!=nums[fast-1])
{
nums[slow]=nums[fast];
slow++;
}
}
return slow;
}
example-3
题目链接:https://leetcode.cn/problems/merge-sorted-array/
解题思路:
如果从前往后排序,这可能会覆盖掉nums1中的部分数据,所以改为从后向前排,那么最后的数据就是先排序大的;
num1数组的空间是够用的;
如果num1中的数据先排列完毕,那么就将num2中的数据直接复制过去,如果num2中的数据先排列完毕,那么就不需要再进行操作。
代码如下:
void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n){
//如果从前往后排序,这可能会覆盖掉nums1中的部分数据,所以改为从后向前排,那么
//最后的数据就是先排序大的
//num1数组的空间是够用的
//如果num1中的数据先排列完毕,那么就将num2中的数据直接复制过去,如果num2中的数据先排列完毕,那么就不需要再进行操作。
int end1=m-1;
int end2=n-1;
int dest=m+n-1;
while(end1>=0 && end2>=0)
{//当end1或者end2,有一个结束时,就跳出循环
if(nums1[end1]<nums2[end2])
{
nums1[dest--]=nums2[end2--];
}
else
{
nums1[dest--]=nums1[end1--];
}
}
while(end2>=0)
{
nums1[dest--]=nums2[end2--];
}
}