算法-数组中重复的数字
题目:在一个长度为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 ; } |
作者:FlyElephant
出处:http://www.cnblogs.com/xiaofeixiang
说明:博客经个人辛苦努力所得,如有转载会特别申明,博客不求技惊四座,但求与有缘人分享个人学习知识,生活学习提高之用,博客所有权归本人和博客园所有,如有转载请在显著位置给出博文链接和作者姓名,否则本人将付诸法律。
出处:http://www.cnblogs.com/xiaofeixiang
说明:博客经个人辛苦努力所得,如有转载会特别申明,博客不求技惊四座,但求与有缘人分享个人学习知识,生活学习提高之用,博客所有权归本人和博客园所有,如有转载请在显著位置给出博文链接和作者姓名,否则本人将付诸法律。
标签:
算法
, Objective-C
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述
2013-07-07 五险一金 社保基数 住房公积金基数以及个税(By FlyElephant)