leetcode解题之 26. Remove Duplicates from Sorted Array Java版

本文介绍了一种高效算法,用于原地删除有序数组中的重复元素,确保每个元素仅出现一次。通过使用双指针技巧,该方法在O(n)时间复杂度内完成,且仅使用O(1)额外空间,符合题目要求。

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

  1. Remove Duplicates from Sorted Array

Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.

  Example 1:
    
    Given nums = [1,1,2],
    
    Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
    
    It doesn't matter what you leave beyond the returned length.

题目翻译:
给定一个有序数组,原地删除重复元素,使得每个元素只出现一次,并返回新的长度。
不为另一个数组分配额外空间,必须用常量内存做到这一点。
例如,
给定输入数组 A = [1,1,2],
函数应返回长度 = 2,A现在是[1,2]。

解题思路

题解方法是双指针,一个指针i只记录唯一的元素的并且帮助记录长度,一个指针 j 往前找。

class Solution {
    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;
   }
}
运行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值