leetcode 26: Remove Duplicates from Sorted Array

来源:互联网 发布:武汉理工大学网络教学 编辑:程序博客网 时间:2024/06/16 11:11

问题描述:

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.

思路:

首先想到把重复的全部置换到数组后面去,但在筛选重复数的过程中,我们需要用到“有序”这个特点,所以不能在此过程中置换。因此想到标记的办法,将重复数的值全部改成数组第一个数的值(第一个数不可能是重复数啊这还用说)。然后在后面再一并交换移动到后面去。

代码:

class Solution {public:    int removeDuplicates(vector<int>& nums) {        int length = nums.size();        int new_length = length;        int head;        if (length > 0) head = nums[0];        int temp = head;        for (int i = 1; i < length; i++)   //change all the duplicates to be head value        {            if (nums[i] == temp) { nums[i] = head; new_length--; }            else temp = nums[i];        }        int dup = 1;        for (; dup < length; dup++)     //detect the first duplicates position        {            if (nums[dup] == head)                break;        }        for (int i = 1; i < length; i++)        {            if (nums[i] != head)            {                if (dup < i)                {                    nums[dup] = nums[i];                    nums[i] = head;                    for (int j = dup; j < length; j++)  //detect the next duplicates position                    {                        if (nums[j] == head)                        {                            dup = j;                            break;                        }                    }                }            }        }        return new_length;    }};
0 0
原创粉丝点击