[LeetCode] 26. Remove Duplicates from Sorted Array

</br>


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 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 new length.


Solution

Since the array is sorted, the standard non-repeated array should be like.

nonRepeatedNums = [1,2,5,7,9,...]

Compared with the original array,

nums = [1,2,2,5,5,7,9,9,...]

We can clearly find out that if the array is sorted, the index should be smaller than its value as the most standard sorted array should be [1,2,3,4,5,6,7,8,9,...] , and if other array has index bigger than its value, there must be replicate numbers before itself.

This should be somewhat practical but still not easy enough to implement code.

Hence, we only have to compare the array with the ones that is already identified as non-repeated, once identified as a new non-repeated number, we can put this number in the array.

Instead of taking care of every element in the array, we only have to overwrite the front part of the array every time we identify a non-repeated number.

The code should do the rest explaining.

Java

public class Solution {
    public int removeDuplicates(int[] nums) {
        
        int i = nums.length>0 ? 1:0;
        
        for (int n : nums)
            if (n > nums[i-1])
                nums[i++] = n;
                
        return i;
    }
}

</br>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,967评论 0 23
  • 对不起,谢谢。 一直都不知道应该怎样去权衡一些人为你付出的真心,不知道要以什么样的方式去回报别人为你付出的真心,...
    你们这群小猪阅读 186评论 0 0
  • 下面的经历你一定似曾相识: 1.明明起床得很早,信心满满可以早到的,可最后却还是迟到,被同事取笑,最后陷入深深的自...
    自由ai流浪阅读 436评论 0 0
  • 深夜,离十二点还差几分,突然收到一位微信好友的消息:“你总在逃避问题”。我悻悻然回答他,“我没有”。其实,好友说的...
    水晶墨阅读 162评论 0 0
  • 到底是从什么时候开始,我抗拒回家,不愿面对父母,同时,又挣扎在愧疚、自我厌恶、自我谴责的复杂情绪中。 独自在外地工...
    二童阅读 297评论 0 0