2.1.1Remove Duplicates from Sorted Arr

 1 /*
 2 题目:2.1.1 Remove Duplicates from Sorted Array
 3 Given a sorted array, remove the duplicates in place such that each element appear only once
 4 and return the new length.
 5 Do not allocate extra space for another array, you must do this in place with constant memory.
 6 For example, Given input array A = [1,1,2],
 7 Your function should return length = 2, and A is now [1,2]
 8 */
 9 /*
10 分析:数组中元素去重问题
11 要求:不能申请新空间,需要在原来的数组空间上操作
12 思路:1、用两个指针指向前后两个元素
13     2、比较前后两个元素是否相同
14     3、不同则将后一个元素写入前一个指针所表示的数组中
15     4、直到数据末尾
16 
17 注:该方法只适合已排好顺序的数组
18 */
19 #include <stdio.h>
20 #include <stdlib.h>
21 
22 //写一个类,类里面的public成员中放这些函数(注意类的书写规范:1、类名大写 2、中括号后有分号)
23 class Solution{
24 public:         
25     //类内实现函数(区分类内定义,类外实现。作用域限定符的使用)
26     int removeDuplicates(int A[],int n){  //数组作为函数参数如何传递?
27         if(n == 0) return 0; //数组长度为零的情况
28 
29         int index = 0;
30         for(int i = 1;i < n;i++){
31             if(A[index] != A[i])
32                 A[++index] = A[i]; 
33         }
34         return index + 1;
35     }
36 };
37 int main()
38 {
39     int A[] = {1,2,2,3,5,7,7,8,};
40     Solution s1;
41     int n = s1.removeDuplicates(A,8);//数组传参,只用传递数组名
42 
43     printf("个数:%d
",n);
44     for(int j =0;j < n;j++)
45         printf("%d ",A[j]);
46 
47     system("pause");
48     return 0;
49 }
原文地址:https://www.cnblogs.com/Star-Lit/p/8504011.html