{1,22,56,53,34,51,77}这是一个数组,如何不用内部函数和遍历数组的方法判断出 53 在这个数组里。(面试问题)

2015-07-10 22:02:34 +08:00
 ning1022

我想到了php中的in_array()函数。但是很明显不对。

11554 次点击
所在节点    PHP
119 条回复
Septembers
2015-07-10 23:11:25 +08:00
@est 构造随机数作为索引随机命中 如果匹配就。。。。。?
ning1022
2015-07-10 23:13:32 +08:00
@adspe 感觉考察的是算法。但是我不也不会!
ning1022
2015-07-10 23:14:05 +08:00
@qiayue 应该是同功能的函数,比如in_array()
est
2015-07-10 23:14:22 +08:00
@Septembers 文字上可以不叫遍历,本质上不也是挨着挨着一个一个问么。
ning1022
2015-07-10 23:15:24 +08:00
@simman 我感觉这个不是正确答案!
ning1022
2015-07-10 23:18:46 +08:00
@est 我要是面试成功的话,我一定问问他这个答案,我很无语,查了很多资料,感觉是算法。
ning1022
2015-07-10 23:20:35 +08:00
@mouhong 大数据算法?感觉有点抽象!
ning1022
2015-07-10 23:22:57 +08:00
@Septembers 这个是个好思路,哈哈!
dingyaguang117
2015-07-10 23:23:18 +08:00
可以反证 必须要遍历的
Septembers
2015-07-10 23:27:56 +08:00
hackpro
2015-07-10 23:30:57 +08:00
@dallaslu 正解 某年acm切的題
如果特別考察你算法的話 翻翻拓撲的東西 以前數學課上過 現在記不清了
nozama
2015-07-10 23:31:46 +08:00
bool find1(int num, int index, int* arr)
{
return num == arr[index];
}
bool find3(int num, int base_index, int* arr)
{
return find1(num, base_index, arr) || find1(num, base_index + 1, arr) || find1(num, base_index + 2);
}

bool find6(int num, int base_index, int* arr)
{
return find3(num, base_index, arr) || find3(base_index + 4);
}

int main()
{
int arr[] = {1,22,56,53,34,51,77};
auto found = find1(53, arr) || find6(53, 1, arr);
}
nozama
2015-07-10 23:35:14 +08:00
随手写的, 有些typo
ning1022
2015-07-10 23:37:13 +08:00
@Septembers 我感觉他考的是效率或者算法。当时我还想到了二叉树,从中间分,log2N。(以前考计算机二级的时候学的,现在都忘了,不知道对不对,呵呵)
zhaiduo
2015-07-10 23:39:11 +08:00
78
imyip
2015-07-10 23:42:34 +08:00
二分法?
ning1022
2015-07-10 23:42:47 +08:00
@nozama 你这好像没有遍历也没有内部函数,牛呀,但是我得抽空测试下,这个好像是C写的。
dallaslu
2015-07-10 23:46:15 +08:00
@ningyuqiao456 如果数组有序,二分还可以
nozama
2015-07-10 23:46:34 +08:00
@ningyuqiao456 我测试过了, 应该没错。
//====================
bool find1(int num, int index, int* arr){ return num == arr[index]; }

bool find3(int num, int base_index, int* arr){ return find1(num, base_index, arr) || find1(num, base_index + 1, arr) || find1(num, base_index + 2, arr); }

bool find6(int num, int base_index, int* arr){ return find3(num, base_index, arr) || find3(num, base_index + 4, arr); }

bool find7(int num, int* arr, size_t size){ return find1(num, 0, arr) || find6(num, 1, arr); }

int main()
{
int arr[] = {1,22,56,53,34,51,77};

auto found = find7(53, arr, sizeof(arr));

assert(found);
}
mulog
2015-07-10 23:46:40 +08:00
我觉得需要定义一下遍历。。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/204852

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX