【数组OJ题】

删除排序数组中的重复项
题目来源

给你一个 升序排列 的数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。元素的 相对顺序 应该保持 一致 。然后返回 nums 中唯一元素的个数。

c 复制代码
int removeDuplicates(int* nums, int numsSize) {
    //使用三个指针
    // [0,0,1,1,1,2,2,3,3,4]
    //  0 1 2 3 4 5 6 7 8 9
    // 5
    int cur = 0;
    int ret = 1;
    int begin = 0;
    int n = numsSize;

    while (ret < n) {
        if (nums[cur] == nums[ret]) {
            ret++;
        }
        else {
            nums[begin] = nums[cur];
            begin++;
            cur = ret;
            ret++;
        }
    }
    nums[begin] = nums[cur];
    begin++;
    return begin;
}
c 复制代码
int removeDuplicates(int* nums, int numsSize) {
    //三指针
    int cur = 0;
    int tail = 1;
    int temp = 0;

    // [0,0,1,1,1,2,2,3,3,4]
    while (tail < numsSize)
    {
        if (nums[cur] == nums[tail]) {
            tail++;
        }
        else {
            nums[temp] = nums[cur];
            temp++;
            //temp每次存储完成之后都会加一
            //0之后变为1、1之后变为2...
            //所以说temp就是数据元素个数
            cur = tail;
            tail++;
        }
    }

    //还需要把最后一个数据加上
    nums[temp] = nums[cur];
    //
    temp++;

    return temp;
}

合并两个有序数组
题目来源

给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n ,分别表示 nums1 和 nums2 中的元素数目。

c 复制代码
void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n){
    //使用m和n
    // nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
    // [1,2,2,3,5,6]
    int end1 = m-1;
    int end2 = n-1;
    int ends = m+n-1;
    while((end1>=0)&&(end2>=0)){
        if(nums1[end1]>=nums2[end2]){
            nums1[ends] = nums1[end1];
            end1--;
            ends--;
        }else{
            nums1[ends] = nums2[end2];
            end2--;
            ends--;
        }
    }
    //end1 和 end2
    //if end2先走完了 啥也不用变
    //if end1先走完了 需要将end2剩余元素放到nums1中
    while(end2>=0){
        nums1[ends] = nums2[end2];
        end2--;
        ends--;
    }
}
c 复制代码
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 (nums2[end2] >= nums1[end1]) {
            nums1[end] = nums2[end2];
            end2--;
            end--;
        }
        else {
            nums1[end] = nums1[end1];
            end1--;
            end--;
        }
    }
    while (end2 >= 0)
    {
        nums1[end] = nums2[end2];
        end2--;
        end--;
    }
}
相关推荐
黎雁·泠崖几秒前
【线性表系列入门篇】从顺序表到链表:解锁数据结构的进化密码
c语言·数据结构·链表
橘颂TA35 分钟前
【剑斩OFFER】哈希表简介
数据结构·算法·散列表
小尧嵌入式36 分钟前
c++红黑树及B树B+树
开发语言·数据结构·c++·windows·b树·算法·排序算法
optimistic_chen37 分钟前
【Redis 系列】常用数据结构---ZSET类型
数据结构·数据库·redis·xshell·zset·redis命令
tobias.b41 分钟前
408真题解析-2009-10-数据结构-排序
数据结构·算法·排序算法·408考研·408真题·真题解析
好奇龙猫1 小时前
【大学院-筆記試験練習:线性代数和数据结构(2)】
数据结构·线性代数·决策树
Wuliwuliii1 小时前
贡献延迟计算DP
数据结构·c++·算法·动态规划·dp
D_FW1 小时前
数据结构第一章:绪论
数据结构·考研
于齐龙1 小时前
2025年12月24日 - 数据结构
数据结构
GrowingYi2 小时前
算法基础技术栈
数据结构·算法