有序整型数组A,大小为n,请给出一个O(n)的算法,删除重复元素,O(1)空间

来源:互联网 发布:windows禁止arp 编辑:程序博客网 时间:2024/05/22 21:10

/*
 *   给定排好序的整型数组A,大小为n,请给出一个O(n)的算法,删除重复元素,且不能使用额外空间。
 *
 *   提示:既然有重复,必有冗余空间。将元素放入数组的前面,并记录下次可放位置,不断向后扫描即可。
 */

 

解法如提示所示,代码如下~

 

#include <iostream>using namespace std;int arr[] = {1,2,3,3,3,3,4,5,5,5,6,7,7,7,8};//int arr[] = {1,2,3,4,5,6,7,8};/* *大小为n的数组,删除其中的重复元素 *返回删除重复元素后,数组中剩下的元素个数 */int  solve(int n){if(n < 0)//检查参数return -1;  int candidate = arr[0];   //取数组第一个元素int count = 1;            //去除重复元素后,最后数组的元素个数for(int i=1; i<n; ){if(arr[i] != candidate){arr[ count++ ] = candidate = arr[i]; //更新candidatei++;}else  //出现重复元素{int j = i;while(j < n && arr[j] == candidate )  j++;  //向后找到第一个不相同的元素,或者遍历至数组末尾if(j < n)  //j下标指向的数组元素存在,且不等于candidate{arr[count++] = candidate = arr[j];}i = j+1;}}return count;}int main(){int n = sizeof(arr) / sizeof(int);int res = solve(n);//查看结果for(int i=0; i<res; i++)cout<<arr[i]<<" ";cout<<endl;}


 

欢迎读者留言探讨~O(∩_∩)O~

 

 

原创粉丝点击