[leetcode]80. Remove Duplicates from Sorted Array II有序数组去重(单个元素可出现两次)

本文介绍了一种在原地修改输入数组以去除重复元素的方法(允许每个元素最多出现两次),并提供了一个具体的Java实现示例。

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice 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.

Given nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.

It doesn't matter what you leave beyond the returned length.

 

题意:

有序数组去重(允许某个元素重复出现两次)

 

思路:

仍然是在尽量不开新空间的情况下,直接在原数组中进行操作。(当然,我们可以想象另开了一个新的数组存储去重后的结果)

指针i来遍历原数组。

指针j 从 index 2 开始, 因为index 为 0、1 的元素是什么牛鬼蛇神都不重要。

指针j 接受指针i扫过的、符合条件的元素。

指针j所到之处,便是新“数组”新生之时。

 

代码:

 1 class Solution {
 2     public int removeDuplicates(int[] nums) {
 3         // corner case
 4         if(nums.length == 0 || nums == null) return 0;
 5         int j = 2; 
 6         for(int i = 2; i < nums.length; i++){
 7             if(nums[i] != nums[j-2]){
 8                 nums[j] = nums[i];
 9                 j++;
10             }
11         }
12       return j;  
13     }
14 }

 

转载于:https://www.cnblogs.com/liuliu5151/p/9136757.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值