【数组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--;
    }
}
相关推荐
杰克尼1 小时前
BM5 合并k个已排序的链表
数据结构·算法·链表
xiaolang_8616_wjl2 小时前
c++文字游戏_闯关打怪
开发语言·数据结构·c++·算法·c++20
hqxstudying2 小时前
Java创建型模式---单例模式
java·数据结构·设计模式·代码规范
sun0077003 小时前
数据结构——栈的讲解(超详细)
数据结构
ゞ 正在缓冲99%…7 小时前
leetcode918.环形子数组的最大和
数据结构·算法·leetcode·动态规划
努力写代码的熊大9 小时前
单链表和双向链表
数据结构·链表
Orlando cron10 小时前
数据结构入门:链表
数据结构·算法·链表
许愿与你永世安宁14 小时前
力扣343 整数拆分
数据结构·算法·leetcode
Heartoxx15 小时前
c语言-指针(数组)练习2
c语言·数据结构·算法
杰克尼16 小时前
1. 两数之和 (leetcode)
数据结构·算法·leetcode