標籤:
演算法,在學校的時候就掌握的不牢固,如今還是要還上了。
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開發——有序數組去重的幾種演算法