算法-数组中重复的数字
生活随笔
收集整理的這篇文章主要介紹了
算法-数组中重复的数字
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目:在一個長度為n的數(shù)組里的所有數(shù)字都在0到n-1的范圍內(nèi)。數(shù)組中某些數(shù)字是重復(fù)的,但不知道有幾個數(shù)字重復(fù)了,也不知道每個數(shù)字重復(fù)了幾次。請找出數(shù)組中任意一個重復(fù)的數(shù)字。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | //原文地址:http://www.cnblogs.com/xiaofeixiang -(NSInteger)duplicate:(NSMutableArray?*)array{ ????for?(NSInteger?i=0;i<[array count];i++) { ????????while?(i!=[array[i] integerValue]) { ????????????if?([array[[array[i] integerValue]] isEqualTo:array[i]]) { ????????????????return?[array[i] integerValue]; ????????????} ????????????NSInteger??temp=[array[[array[i] integerValue]] integerValue]; ????????????array[[array[i] integerValue]]=array[i]; ????????????array[i]=[NSNumber?numberWithInteger:temp]; ????????} ????} ????return?-1; } |
測試代碼:
| 1 2 3 4 | NSMutableArray??*dataSource=[[NSMutableArray?alloc]initWithObjects:@"2",@"3",@"1",@"4",@"1",?nil]; NSInteger??index=[search duplicate:dataSource]; NSLog(@"重復(fù)的數(shù)字:%ld",index); NSLog(@"技術(shù)交流群:%@",@"228407086"); |
還存在另外一種解法,比較簡單,很繞,有興趣的可以研究一下:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | -(NSInteger)duplicate:(NSMutableArray?*)array{ ????for?(NSInteger?i= 0 ; i<[array count]; i++) { ????????NSInteger?index =[array[i] integerValue]; ????????if?(index >= [array count]) {ki,k?? /.m m,l;''j im9l./ ????????????index -= [array count]; ????????} ????????if?([array[index] integerValue] >= [array count]) { ????????????return?index; ????????} ????????array[index]=[NSNumber?numberWithInteger:[array[index] integerValue] + [array count] ]; ????} ????return?- 1 ; } |
總結(jié)
以上是生活随笔為你收集整理的算法-数组中重复的数字的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 未来3年,大数据市场规模将达到万亿元
- 下一篇: 云计算产业被市场广泛看好 未来市场规模达