【LeetCode】Remove Duplicates from Sorted Array I && II

133 篇文章 0 订阅
121 篇文章 2 订阅

I、每个数据只允许出现1次
Remove Duplicates from Sorted Array 
Total Accepted: 7116 Total Submissions: 21546 My Submissions
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].
II、每个数据最多允许出现2次
Remove Duplicates from Sorted Array II 
Total Accepted: 4799 Total Submissions: 16270 My Submissions
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1,1,1,2,2,3],
Your function should return length = 5, and A is now [1,1,2,2,3].
因为不能使用多余的空间,所以需要扫描一遍完成。
如果空间多一点的话,这两道题完全没有什么压力,很简单,直接暴力搜索,赋值即可。
说一说基本思路。
因为是有序数组,所以在最开始声明int start = 0。
然后扫描一遍数组,判断当前数据和start是否相等。
对于I,只需要判断当前值和A[start]是否相等,如果不相等,
start++;
A[start] = A[i],
这样就完成了一次判断操作
否则的话继续循环,扫描下一个值。
对于II,需要判断当前值出现的次数。
如果A[start] != A[i],出现的次数应该是1,那么
和I一样
start++;
A[start] = A[i],
否则的话,需要判断,当前数字出现的次数是否大于等于2,如果>=2,那么继续循环扫描下一个数字,
如果<2,直接赋值即可。

I、Java AC

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

II、Java AC

public class Solution {
    public int removeDuplicates(int[] A) {
        if(A == null || A.length == 0){
            return 0;
        }
        int start = 0;
        int len = A.length;
        int twice = 1;
        for(int i = 1; i < len; i++){
            if(A[i] != A[start]){
                twice = 1;
                start++;
                A[start] = A[i];
            }else{
                twice++;
                if(twice <= 2){
                    start++;
                    A[start] = A[i];
                }
            }
        }
        return start+1;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值