您的位置:首页 > 其它

快速找出重复的数

2016-10-29 22:21 113 查看
某式面试官问了一道这样的题,1到N(N为正整数)共N个正整数,其中有一个数重复一次覆盖了另外一个数,比如:9,3,7,5,1,8,2,4,5,那么其中5重复一次,相当于覆盖了6,那么,请找出这个重复的数。

当时提供了HASH法,但人家不满意,直接pass了。

如果能想到循环链表式的数据结构,那么就很容易有思路了。

1 #include <iostream>
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <string>
5 #include <string.h>
6 #include <algorithm>//reverse
7 #include <vector>
8 using namespace std;
9 #define debug(x) cout << #x << " at line " << __LINE__ << " is: " << x << endl
10
11 void f(int *s,int n){
12     int w = 0, f=0;
13     do{
14         w = s[w]-1;
15         f = s[s[f]-1]-1;
16     }while(w != f);
17     printf("%d\n", w+1);
18 }
19
20 int main() {
21     int N = 7;
22     int arr[]={2,5,3,4,6,7,3};
23     f(arr, N);
24 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐