Chinaunix首页 | 论坛 | 博客
  • 博客访问: 97764
  • 博文数量: 21
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 200
  • 用 户 组: 普通用户
  • 注册时间: 2014-10-11 22:44
个人简介

HUST16届准毕业生,发奋求职中...

文章分类

全部博文(21)

文章存档

2015年(17)

2014年(4)

我的朋友

分类: C/C++

2015-07-10 12:15:51

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 A = [1,1,2],

Your function should return length = 2, and A is now [1,2].



解法:设置两个指针ptr1,和ptr2,其中ptr1指向不重复的数字末尾,ptr2则用来遍历数组,当发现ptr2和它之前指向的数不一致时,就将ptr1++,并将ptr2指向的值赋值给ptr1。当ptr2遍历结束,ptr1指向的就是新数组的末尾,通过指针相减即可得到新数组的长度。

C语言实现:

点击(此处)折叠或打开

  1. int removeDuplicates(int* nums, int numsSize) {
  2.     if(NULL == nums)
  3.         return NULL;
  4.     if(numsSize <=1)
  5.         return numsSize;
  6.     int *ptr1,*ptr2;
  7.     int pre,i;
  8.     ptr1 = nums;
  9.     ptr2 = nums;
  10.     for(i=0;i<numsSize-1;i++)
  11.     {
  12.         pre = *ptr2;
  13.         ptr2++;
  14.         if(*ptr2 != pre)
  15.         {
  16.             ptr1++;
  17.             *ptr1 = *ptr2;
  18.         }
  19.     }
  20.     return (ptr1-nums)+1;
  21.     
  22. }

阅读(1267) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~