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

Hide Tags :Array ,Two Pointers
题目26:输入一个已经拍好序的数组,其中有可能有重复数据,找出重复数据,栓出多余的重复数据,只保留一个重复数据。
思路:记录其中的重复数据次数,比如其中有三个数据都是5,那么重复次数就为2。将后面的数据依次填充到重复数据位置.

if(nums[i] == nums[i+1]) count++;
else nums[i+1-count] = nums[i+1]; 

题目27:本题和题26类似,27题要求将与给定数据val重复数据都栓出,不保留任何一个重复数据,方法类似,记录重复次数比26题多1个就行

if(nums[i] == val) count++;
else nums[i-count] = nums[i]; 
#include <stdlib.h>
#include <stdio.h>
//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.
  */
//思路一直累加重复的个数,数组第i 位= i - 重复的个数
int removeDuplicates(int* nums, int numsSize) {

    int i = 0;
    int count = 0;

    for(i=0;i<numsSize-1;i++)
    {
        if(nums[i] == nums[i+1])
        {
            count++;
        }
        else
        {
            nums[i+1-count] = nums[i+1];    
        }   

    }

    return numsSize-count;
}

//27 :Remove Element 
//Given an array and a value, remove all instances of that value in place and return the new length.
//The order of elements can be changed. It doesn't matter what you leave beyond the new length.

int removeElement(int* nums, int numsSize, int val) {
    int i = 0;
    int count = 0;
    for(i=0;i<numsSize;i++)
    {
        if(nums[i] == val)
        {
            count++;
        }
        else
        {
           nums[i-count] = nums[i]; 
        }
    }

    return numsSize-count;
}


int main()
{
    int n[10] = {1,2,3,3,3,4,5,5,6,7};
    int s[10] = {1,2,3,4,5,6,7,8,9,10};
    int r = removeDuplicates(s,10);
    printf("r = %d\n",r);
    int i = 0 ;
    for(i=0;i<r;i++)
    {
        printf("n[%d] = %d\n",i,n[i]);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值