當前位置:
首頁 >
算法-数组中重复的数字
發布時間:2025/4/16
36
豆豆
生活随笔
收集整理的這篇文章主要介紹了
算法-数组中重复的数字
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:在一個長度為n的數組里的所有數字都在0到n-1的范圍內。數組中某些數字是重復的,但不知道有幾個數字重復了,也不知道每個數字重復了幾次。請找出數組中任意一個重復的數字。
| 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(@"重復的數字:%ld",index); NSLog(@"技術交流群:%@",@"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 ; } |
總結
以上是生活随笔為你收集整理的算法-数组中重复的数字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 未来3年,大数据市场规模将达到万亿元
- 下一篇: 云计算产业被市场广泛看好 未来市场规模达