问题描述:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
难度等级: easy
个人理解:
开始没有读懂题意,所以觉得如果在有序的情况下,那么只需要遍历一遍就可以,想法是 :
1、从后往前找到比这个数小的数,记下下标$last_index
2、从前面$start_index(初始值为0)以及到$last_index开始,一前一后进行加,如果大于$target_num,那么,last_index --, 如果小于$target_num,那么就进行 $start_index++,一直到 $last_index >= $start_index 为止,中间找到则直接返回 start_index和last_index
没想到的点以及踩到的坑:
1、我按照之前的想法来做,但是发现没有进行排序,遂该想法作罢
2、那我就直接每一个进行自己的进行查找不就完事了吗,虽然愚蠢,但是好歹也是解了,然后按照这个想法写代码,坑:
a. 如果里面存在一样的怎么呢?比如 $target_num为6, 数组是 [3,3,5] ,那么返回[0,1] 我返回 [0,0] 问题就在这儿,array_search 只会找首次出现的,没办法,只能按照 array_slice在进行查找
b. 切分之后但是返回的下标不正确,仔细看了下,问题在于,我切分了,但是第二个下标并没有从开始计算,而是我需要把前面裁剪的给加上,OK,好了
c. 最后一个坑是我需要加1,为什么呢?因为我是将 前面的下标来计算的,但是 如果是长度的话,需要+1,因为下标总比 长度少1
下面贴上本次代码,写的一般,实在汗颜,需要查看别人的想来做进行优化了
class Solution {
/**
* @param Integer[] $nums
* @param Integer $target
* @return Integer[]
*/
function twoSum($nums, $target) {
if(empty($nums)){
return [];
}
for($i=0;$i<count($nums)-1;$i++){
if(in_array($target-$nums[$i],$nums)){
$new_index = array_search($target-$nums[$i], array_slice($nums, $i+1));
if($new_index !== false){
return [$i, $new_index+$i+1];
}
}
}
return [];
}
}