题目:数组[1,3,5,8,7] 找出两个数组和为8的数组下标(0,4),(1,2)
PHP代码实现
public function index_sum(){
$array = [1,3,5,8,7];
$sum = 8;
for($i=0;$i<count($array);$i++){
$other = $sum - $array[$i];
for($j=$i+1;$j<count($array);$j++){
if($array[$j] == $other){
print_r("($i,$j)");
}
}
}
}
Golang代码实现
func main(){
array := [5]int{1,2,5,8,7}
myTest(array,8)
}
func myTest(a [5]int, target int) {
// 遍历数组
for i := 0; i < len(a); i++ {
other := target - a[i]
// 继续遍历
for j := i + 1; j < len(a); j++ {
if a[j] == other {
fmt.Printf("(%d,%d)\n", i, j)
}
}
}
}