2.1.1Remove Duplicates from Sorted Arr
生活随笔
收集整理的這篇文章主要介紹了
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",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
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的2.1.1Remove Duplicates from Sorted Arr的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我的Docker-CE学习笔记(03)
- 下一篇: 浅谈 Scala 中下划线的用途