【Leetcode】100. Remove Duplicates from Sorted Array

100. Remove Duplicates from Sorted Array

Description

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.

Example

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

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

Solution

idea:从数组开头到 nums[i] 的所有数均为不重复的数。

i 从 0 开始(第一个数),若遇到一个和第一个数不一样的数(即第二个数),则将 i 进一位并将 nums[i] 赋值为第二个数,依次类推,直到数组最后一个数。因此,共有 i+1 个数是不重复的数。

public class Solution {
    /**
     * @param A: a array of integers
     * @return : return an integer
     */
    public int removeDuplicates(int[] nums) {
        // write your code here
        if(nums == null || 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;
    }
}

Follwup Question

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].

Solution

额外用一个 boolean 表示是否可以添加重复元素,只有 boolean 为 true 时才能添加重复元素。当添加一个新元素时,boolean 设置为 true,当添加一个重复元素后,boolean 设置为 false。

public class Solution {
   /**
    * @param A: a array of integers
    * @return : return an integer
    */
   public int removeDuplicates(int[] nums) {
       // write your code here
       if(nums == null || nums.length == 0){
           return 0;
       }

       boolean twice = true;
       int i = 0;
       for(int j = 1; j < nums.length; j++){
           if(nums[j] != nums[i]){
               i++;
               nums[i] = nums[j];
               twice = true;
           }else if(twice){
               i++;
               nums[i] = nums[j];
               twice = false;
           }
       }
       return i + 1;
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值