Leetcode:Remove Duplicates from Sorted Array与Remove Element

本文详细介绍了如何使用常数内存去除数组中的重复元素,并提供了删除数组中特定值的实现方法。通过实例演示了遍历数组的两种方式,并解释了如何优化空间复杂度。同时,文章还总结了遍历数组的通用策略,包括从两端开始遍历和设置中间指针进行记录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Remove Duplicates from Sorted Array:

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

设置一个变量size,初始化为0。遍历数组,如果A[i]不等于A[size],则为不重复的数,把A[i]的值赋给A[size],size加1,i继续遍历数组后面的数。最后,size+1的即为数组中不重复的数的个数。

实现代码如下:

public class Solution {
    public int removeDuplicates(int[] A) {
        if (A == null || A.length == 0) {
            return 0;
        }
        
        int size = 0;
        for (int i = 0; i < A.length; i++) {
            if (A[i] != A[size]) {
                A[++size] = A[i];
            }
        }
        return size + 1;
    }
}


Remove Element:

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

设置变量i从头遍历数组,再设置一个变量end指向数组的末尾。如果遇到A[i]等于目标数字,把A[end]的值赋给A[i],在继续比较A[i]与目标数字,如果不相等,则遍历数组下一个元素,循环的条件为:i<=end.最终,数组的前end+1数,即为所求。

实现代码:

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        int i=0;
        int end=n-1;
        while(i<=end)
        {
            if(A[i]==elem)
            {
                A[i]=A[end--];
            }
            else
            i++;
        }
        return end+1;
    }
};


这两题难度都不大,把它们放在一起是因为可以总结一下遍历数组的方法,可以分别从两头遍历。还可以设置一个中间遍历,在遍历的过程中记录所需要的数值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值