一道有趣的GOOGLE面试题

来源:互联网 发布:淘宝文胸打造爆款经验 编辑:程序博客网 时间:2024/06/05 19:35
//GOOGLE面试题//一个大小为n的数组,里面的数都属于范围[0, n-1],有不确定的重复元素,找到至少一个重复元素,要求O(1)空间和O(n)时间。//By MoreWindows (http://blog.csdn.net/MoreWindows)#include <stdio.h>const int NO_REPEAT_FLAG = -1;int FindRepeatNumberInArray(int *a, int n){for(int i = 0; i < n; i++){int nRealIndex = a[i] >= n ? a[i] - n : a[i];if (a[nRealIndex] >= n) //这个位置上的值大于n说明已经是第二次访问这个位置了return nRealIndex;elsea[nRealIndex] += n;}return NO_REPEAT_FLAG; //数组中没有重复的数}void PrintfArray(int a[], int n){for (int i = 0; i < n; i++)printf("%d ", a[i]);putchar('\n');}int main(){printf("    白话经典算法系列之十一 一道有趣的GOOGLE面试题解法2\n");      printf(" -- by MoreWindows( http://blog.csdn.net/MoreWindows ) --\n\n"); const int MAXN = 10;//int a[MAXN] = {2, 4, 1, 5, 7,  6, 1, 9, 0, 2};int a[MAXN] = {0, 1, 2, 3, 4,  5, 6, 7, 8, 0};printf("数组为: \n");PrintfArray(a, MAXN);int nRepeatNumber = FindRepeatNumberInArray(a, MAXN);if (nRepeatNumber != NO_REPEAT_FLAG)printf("该数组有重复元素,此元素为%d\n", nRepeatNumber);elseprintf("该数组没有重复元素\n");return 0;}

原创粉丝点击