删除数组中重复的数字

问题:一个动态长度可变的数字序列,以数字0为结束标志,要求将重复的数字用一个数字代替,例如:

将数组 1,1,1,2,2,2,2,2,7,7,1,5,5,5,0 转变成1,2,7,1,5,0 问题比较简单,要注意的是这个数组是动态的。

 

 

======================

 

#include <iostream>
#include <vector>
using namespace std;

 

//使用标准容器

void Reduce(int *a,std::vector<int> &st)
{
 st.push_back(a[0]);
 for(int i=0;st[st.size()-1]!=0;i++)
 {
  if(a[i+1] != a[i])
   st.push_back(a[i+1]);
 }
 //打印
 std::vector<int>::iterator iter;
 for(iter=st.begin();iter!=st.end();++iter)
  cout<<*iter;
 cout<<endl;
}

 

//直接操作指针
void Reduce1(int *a)
{
 if(a==NULL||a[0]==0)
  return;
 int insert = 1,current = 1;
 while(a[current] != 0)
 {
  if(a[current] != a[current-1])
  {
   a[insert] = a[current];
   insert++;
   current++;
  }
  else
   current++;
 }
 a[insert] = 0;
 for(int i=0;i<=insert;i++)
  cout<<a[i];
 cout<<endl;
}

 

 

int main(int argc,char *argv[])
{
 std::vector<int>::iterator iter;
 std::vector<int> st;
 int a[] = {1,1,1,2,2,5,4,4,4,4,1,0};
 //Reduce(a,st);
 Reduce1(a);
 return 1;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值