code第一部分:数组
code第一部分:數組
?
都說寫代碼一定要自己嘗試,看再多也沒有,確實是的;之前寫過很多,感覺可以分享給大家的就放到博客上,希望激勵自己好好敲代碼。共勉吧!
之前一段時間把關于數組部分的內容做了一些;每周我會集中上傳一次;任務量還是很大的;廢話不多說,開始!
?
首先我把題目按照大的分類,總結起來了,這一部分是數組部分,思維導圖如下
?
第一題 從有序數組中移除重復的數據。
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].
?
分析:
注意是不能分配額外的空間;
如果沒有這個條件,有很多的辦法,重新分配一個數組,沒重復的數據直接存儲;
但是不能分配,就可以直接使用數組的空間實現;
解決方法1 :在數組中留一個索引,索引和下標都往后移,重復就不保存,不重復就保存;
解決辦法2 : 如果對STL很熟悉,就可以直接調用STL做;在#include <algorithm>下,
先調用uniuqe(a,a+n)函數去重,再調用distance來得到去重后數組的大小;
解決辦法3:還是要使用stl中的unique函數,但是如果不知道用distance函數,直接使用
sizeof(a)/sizeof(int)得到去重后數組的大小
?
源代碼如下
?
#include <iostream>#include <algorithm>using namespace std;int removeduplicate(int a[],int n) {int i=1;int index=0;if (n==0){cout<<"the length of array is zero"<<endl;}a[index]=a[0];while(i<n){if (a[index]!=a[i]){a[index]=a[i];index++;i++;}elsei++;}return index+1; }int removeduplicate2(int a[],int n) {return distance(a, unique(a, a + n)); }int removeduplicate3(int a[],int n) {unique(a, a + n);int length=sizeof(a)/sizeof(int);return length; }int main() {int a[3]={1,1,2};int ans=removeduplicate(a,3);cout<<ans<<endl;int b[3]={1,1,2};int ans1=removeduplicate2(b,3);cout<<ans1<<endl;int c[3]={1,1,2};int ans2=removeduplicate2(c,3);cout<<ans2<<endl;return 0; }?
代碼測試通過!
?
轉載于:https://www.cnblogs.com/tao-alex/p/6442969.html
總結
以上是生活随笔為你收集整理的code第一部分:数组的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SparkMLlib回归算法之决策树
- 下一篇: Vertx JDBC 批处理