- php数组是通过hashtable实现的!!!!具体可以参考:https://www.cnblogs.com/s-b-b/p/6222198.html
- foreach遍历数组要比for遍历要快的原因,因为for每次查找元素都要去做一次哈希映射查找对应下标的Bucket,而foreach只需要遍历Bucket链表就好了
- 比如进行赋值
$arr[2]="guangdong";
$arr[1]="beijing";
$arr[3]="shanghai";
$arr[4]="zhejiang";
foreach的输出结果
2 => "guangdong"
1 => "beijing"
3 => "shanghai"
4 => "zhejiang"
数组元素的存储示意图
4. 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
https://segmentfault.com/a/1190000019016557
function twoSum2(array $nums , $target)
{
$res = [];
$nums_match = [];
foreach ($nums as $nums_k => $nums_v){
if(!isset($nums_match[$target-$nums_v])){
$nums_match[$target-$nums_v] = $nums_k;
}
}
foreach ($nums as $nums_k => $nums_v){
if (isset($nums_match[$nums_v]) && $nums_match[$nums_v] != $nums_k) {
$res[] = $nums_k;
$res[] = $nums_match[$nums_v];
return $res;
}
}
}