026 删除排序数组中的重复项

LeetCode 第二十六题 删除排序数组中的重复项

给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
示例 1:
给定数组 nums = [1,1,2]
函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。
你不需要考虑数组中超出新长度后面的元素。
示例 2:
给定 nums = [0,0,1,1,1,2,2,3,3,4],
函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。
你不需要考虑数组中超出新长度后面的元素。

遍历一遍数组,如果当前数字和之前的数字相同,则将其删除,然后将后续数组元素向前移动。

Java

    public static int removeDuplicates(int[] nums) {
        if (nums == null || nums.length == 0||nums.length==1)
            return nums.length;
        int current_location = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[current_location] == nums[current_location - 1]) {
                for (int j = current_location; j < nums.length - 1; j++) {
                    nums[j] = nums[j + 1];
                            } else {
                current_location++;
            }
        }
        return current_location;
    }

C++

class Solution
{
public:
    int removeDuplicates(vector<int>&nums)
    {
        if(nums.size()==0||nums.size()==1)return nums.size();
        int current_location=1;
        for(int i=1; i<nums.size(); i++)
        {
            if(nums[current_location]==nums[current_location-1])
            {
                for(int j=current_location; j<nums.size()-1; j++)
                {
                    nums[j]=nums[j+1];
                }
            }
            else
            {
                current_location++;
            }
        }
        return current_location;
    }
};

Python

组后一组测试未通过,因为超时了。有待改进。

class Solution(object):
    def removeDuplicates(self, nums):
        if len(nums) == 0 or len(nums) == 1:
            return len(nums)
        current_position = 1
        for i in range(len(nums)):
            if nums[current_position] == nums[current_position - 1]:
                for j in range(current_position, len(nums) - 1):
                    nums[j] = nums[j + 1]
            else:
                current_position += 1
                if current_position >= len(nums):
                    break
        return current_position

网上看到了更加巧妙的算法,整个时间复杂度只有O(n),它主要是使用了两个坐标i和j,一个跑的快一点,一个跑的慢一点,下面是其代码,学习学习。

public int removeDuplicates(int[] nums) {
    if (nums.length == 0) return 0;
    int i = 0;
    for (int j = 1; j < nums.length; j++) {
        if (nums[j] != nums[i]) {
            i++;
            nums[i] = nums[j];
        }
    }
    return i + 1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值