码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Duplicates from Sorted Array

时间:2015-09-24 10:53:01      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

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.

1、朴素算法

int removeDuplicates(int* nums, int numsSize) {
    int i = 0;
    int j = 1;
    int k = 0;
    if(numsSize < 2)
        return numsSize;
   while (i < numsSize)
    {
        for (; j < numsSize; j++)
        {
            if (nums[i] == nums[j])
                nums[j] = -1;
        }
        i++;
        while (nums[i] == -1)
            i++;
        j = i + 1;
    }
    i = 1;
    j = 2;
    while (j < numsSize)
    {
        while(nums[j] == -1)
            j++;
        nums[i] = nums[j];
        i++;
        j++;
    }
    return i;
}
  • Submission Result: Time Limit Exceeded More Details
  • Last executed input:[-999,-999,-998,-998,-997,-997,-996,-996,-995,-995,-994,-994,-993,-993,-992,-992,-991,-991,-990,-990,-989,-989,-988,
  • 好像输入是可以为-1的,所以把相同的值设置为-1,方法本身就不可行
2、用链表时间复杂度为O(n^2)
typedef struct Node
{
    int data;
    struct Node *next;
}*NODE, *LIST;

int insertList(LIST l, int num)
{
    NODE tmp = NULL;
    while (l->next != NULL)
    {
        l = l->next;
        if (l->data == num)
        {
            return 0;
        }
    }
    tmp = (NODE)malloc(sizeof(struct Node));
    if (tmp == NULL)
    {
        return -1;
    }
    tmp->data = num;
    tmp->next = NULL;
    l->next = tmp;
    return 1;
}

int removeDuplicates(int* nums, int numsSize) {
int i = 0;
    LIST root = (LIST)malloc(sizeof(struct Node));
    root->data = 0;
    root->next = NULL;
    for (int i = 0; i < numsSize; i++)
    {
        insertList(root, nums[i]);
    }
    i = 0;
    while (roo->nextt != NULL)
    {
        root = root->next;
        nums[i] = root->data;
        i++;
    }
    
    return i;
}
  • 果然还是提醒时间复杂度太高

3、网上解答

int removeDuplicates(int* nums, int numsSize) {
  if(!numsSize)
        return 0;  
    int num=1,i;  
    for(i=1;i<numsSize;++i)  
        {if(nums[i]!=nums[i-1])  
            nums[num++]=nums[i];    
        }
    return num;
}
  • 原来是我自己看错了题目,人家只需要相连的相同的值去掉,而不需要过滤掉所有相同的。。。。

Remove Duplicates from Sorted Array

标签:

原文地址:http://www.cnblogs.com/dylqt/p/4834480.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!