【发布时间】:2014-12-19 18:06:30
【问题描述】:
所以,今天我一觉醒来就想到了这个想法。
假设您有一个一长串事物,一个数组,您必须逐一检查以找到与您要查找的内容相匹配的那个。为此,您可以使用for 循环。现在,想象一下你要找的那个几乎在列表的末尾,但你不知道。因此,在这种情况下,假设您检查列表元素的顺序并不重要,那么从最后一个元素而不是第一个元素开始会更方便节省一些时间也许还有记忆。但是,如果你的元素几乎是在开始呢?
那时我想:如果我可以同时开始检查列表两端的元素会怎样?
所以,经过几次尝试,我想出了这个原始示例代码(用 js 编写),在我看来,它可以解决我们上面定义的问题:
fx (var list) {
var len = length(list);
// To save some time as we were saying, we could check first if the array isn't as long as we were expecting
if (len == 0) {
// If it's not, then we just process the only element anyway
/*
...
list[0]
...
*/
return;
} else {
// So, now here's the thing. The number of loops won't be the length of the list but just half of it.
for (var i = 0; i == len/2; i++) {
// And inside each loop we process both the first and last elements and so on until we reach the middle or find the one we're looking, whatever happens first
/*
...
list[i]
list[len]
...
*/
len--;
}
}
return;
};
无论如何,我仍然不能完全确定这是否真的会加快进程或使其变慢或根本没有任何区别。这就是为什么我需要你们的帮助,伙计们。
根据您自己的经验,您怎么看?这真的是让这种过程更快的好方法吗?如果是或不是,为什么?有什么办法可以改善吗?
谢谢各位。
【问题讨论】:
-
通常最好在发布代码时指定您使用的语言。
-
好吧,我不是专门谈论一种语言,但你是对的。假设它写的是js,这是我觉得更舒服的那个