您的位置:首页 > 理论基础 > 数据结构算法

数据结构——算法之(020)( 和为n连续正数序列)

2014-05-27 11:48 253 查看
【申明:本文仅限于自我归纳总结和相互交流,有纰漏还望各位指出。 联系邮箱:Mr_chenping@163.com】

题目:
数组中有一个数字出现的次数超过了数组长度的一半,找出这个数字。
分析:这是一道广为流传的面试题,包括百度、微软和Google 在内的多家公司都

曾经采用过这个题目。要几十分钟的时间里很好地解答这道题,

除了较好的编程能力之外,还需要较快的反应和较强的逻辑思维能力。

题目分析:

一、下面给出三种算法:推荐方法1

(1)删除法:顺序遍历一次数组,每次删除2个数字

(2)标记法:如果数组长度是有限的,申请一个hasn[65536]的数组,然后把数组值映射到其中,最后在顺序遍历hash表从中查找个数超过一半的数

(3)排序法:先排序,返回数组中间的那个值

算法实现:
#include <stdio.h>
/*
** method one
*/
int find_int_more_than_half(int *array, int size)
{
int i = 1;
int count = 1;
int temp = array[0];
for(; i<size; ++i)
{
if(count == 0)
{
temp = array[i];
count++;
continue;
}
if(temp == array[i])
count++;
else
count--;
}
return temp;
}

/*
** hash
*/
int find_int_more_than_half_1(int *array, int size)
{
int i=0;
int	hash[65536] = {0};
for(; i<size; ++i)
{
hash[array[i]]++;
}
for(i=0; i<65536; ++i)
{
if(hash[i] > size/2)
return i;
}
return 0;
}

/*
** sort
*/
int find_int_more_than_half_2(int *array, int size)
{
/*sort*/
int i = 0, j = 0;
int temp;
for(i=0; i<size-1; i++)
{
for(j=i+1; j<size; j++)
{
if(array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
return array[size/2];
}

int main()
{
//int a[] = {1,2,1};
//int a[] = {1,1,1,2,4};
//	int a[] = {1,2,2,4, 2,6,2};
int a[] = {1,3,3,3,2,2,2,1,1,2,1,1,4,1,1,4,1,1,1};
//int a[] = {1,3,2,1,1,2,4,1,1};

printf("--->%d\n", find_int_more_than_half(a, sizeof(a)/sizeof(int)));
printf("--->%d\n", find_int_more_than_half_1(a, sizeof(a)/sizeof(int)));
printf("--->%d\n", find_int_more_than_half_2(a, sizeof(a)/sizeof(int)));
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: