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 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:

這道題的技巧是數(shù)組已經(jīng)排序了,所有的duplicated的元素都是相鄰的。因此可以使用two pointers的思路,用一個i指針遍歷所有元素的同時,用另一個j指針指向當前被拿來作比較的元素,如果i指向的元素等于j指向的元素,則什么都不做;如果i指向的元素不等于j指向的元素,意味著從此以后i指向的元素永遠不會再與j指向的相等。因此可以將i指向的元素放在j指向元素的后一個位置并向后移動j指針(被拿來作比較的元素變成原來的后一個元素了)。

public class Solution 
{
    public int removeDuplicates(int[] nums) 
    {
        int j = 0;
        for(int i = 0; i < nums.length; i ++)
        {
            if(nums[j] != nums[i])
            {
                nums[j + 1] = nums[i];
                j ++;
            }
        }
        return j + 1;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容