Leetcode 26. Remove Duplicates from Sorted Array

一、题目要求

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

二、题目分析

分析:该题目的要求中的关键字,排序,数组,不可以申请额外空间。

对于数组而言,删除重复的元素就会很困难,因此只可以是用 (将要保留的)非重复的元素覆盖掉重复的元素。

1.自己的思路:

  首先,统计非重复的元素的个数,与此同时,用一个值把所有重复的元素代替掉

  然后,把非重复的元素一一前移。

2.最简洁的思路:

  利用两个指针,遍历一次该数组,用不重复的元素覆盖重复的元素

三、代码

public class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums.length==0)
            return 0;
        int j=0;//指向每一个不重复的元素
        for(int i=0;i<nums.length;i++ ){
            if(nums[i]!=nums[j]){
                nums[++j]=nums[i];
            }
        }
        return ++j;
    }
}

  

原文地址:https://www.cnblogs.com/lyr2015/p/6386337.html