1. Remove duplicates in a sorted array
Original link: https://leetcode.cn/problems/remove-duplicates-from-sorted-array/
Idea: Using double pointer algorithm can make the time complexity reach O(1).
The specific process: (explained by drawing)
Code:
int removeDuplicates(int* nums, int numsSize)
{
if(numsSize==0)
return 0;
int i=0,j=1;
int dst=0;
while(j<numsSize)
{
if(nums[i]==nums[j])
{
++j;
}
else
{
nums[dst]=nums[i];
dst++;
i=j;
j++;
}
}
nums[dst]=nums[i];
dst++;
return dst;
}
2. Merge two sorted arrays
Original title link: https://leetcode.cn/problems/merge-sorted-array/
Idea: double pointer arithmetic
Implementation process:
Define two variables end1, end2, respectively point to the last element of the two arrays
Compare the size of num1[end1] and num2[end2], and move the larger value to array one in turn, from the back to the front
As shown below:
Code:
void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n)
{
int end1=m-1,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--];
}
}