iOS開發——有序數組去重的幾種演算法

來源:互聯網
上載者:User

標籤:

演算法,在學校的時候就掌握的不牢固,如今還是要還上了。

 

NSMutableArray *dateMutablearray = [@[] mutableCopy];

  NSArray *array1 = @[@ "1" ,@ "2" ,@ "3" , @ "3" ,@ "4" ,@ "5" ,@ "7" ,@ "9" ,@ "9" , @ "11" ,]; NSMutableArray *array = [NSMutableArray arrayWithArray:array1]; for  ( int  i = 0; i < array.count; i ++) {      NSString *string = array[i];       NSMutableArray *tempArray = [@[] mutableCopy];      [tempArray addObject:string];      for  ( int  j = i+1; j < array.count; j ++) {          NSString *jstring = array[j];          NSLog(@ "jstring:%@" ,jstring);          if  ([string isEqualToString:jstring]) {             NSLog(@ "jvalue = kvalue" );             [tempArray addObject:jstring];           }      }       if  ([tempArray count] > 1) {          [array removeObjectsInArray:tempArray];          i -= 1;     //去除重複資料 新數組開始遍曆位置不變       } }  
最差的演算法:去重,與數組是否有序無關public void noDups(){    //從0開始遍曆    for(int i=0; i<nElems-1; i++){        //與後面每一個比較        for(j=i+1; j<nElems; j++){            //如果相等,後面的所有的項向前移動,總數-1            if(a[i]==a[j]){                for(k=j+1; k<nElems; k++){                    a[j] = a[j+1];                    nElems--;                }            }         }    }}把後面不同的往前public void noDups(){    //數組從小到大排列    this.insertionSort();    int i=0;    //第一個指標    int j=0;    //第二個指標    for(j=1; j<nElems;j++){        //遇到相同的跳過,不同的則加到前面        if(a[j]!=a[i]){            a[++i]=a[j]        }    }    nElems = i+1;}把重複的標記為-1,假設沒有負數public void noDups(){    //數組從大到小排列    this.insertionSort();    final int FLAG = -1;    //重複數字標記    int holdNumber; //被標記的數字個數    //尋找重複項並標記    for(int i=0; i<nElems; i++){        for(int j=i+1; j<nElems; j++){            if(a[i]==a[j]){                a[j] = FLAG;                holdNumber++;            }        }           }    //處理被標記的數字 //思路和第一個一樣    int i=0; //索引位    for(int j=1; j<nElems; j++){    //第一個不可能是重複數        //找到第一個標記位        if(a[j]==FLAG && i==0){            i = j;        }else if(a[j]!=FLAG && i!=0){   //邏輯同第二個演算法            a[i] = a[j];            i++;        }    }    nElems -= holdNumber;}

iOS開發——有序數組去重的幾種演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.