1 Two Sum(easy)

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.

给定一个整数数组,返回两个数字的索引,使它们相加到一个特定的目标。

您可以假设每个输入都只有一个解决方案,而您可能不会使用相同的元素两次。

Given nums = [2, 11, 7, 15], target = 9,

Because nums[0] + nums[2] = 2 + 7 = 9,
return [0, 2].

思考:

1 可以先排序然后使用两个指针向中间遍历  时间复杂度O(nlongn)+O(n) 

while(left < right){
  int temp = nums[left] + nums[right];
  if(temp == target){
    break;
  }else if(temp < target){
   left++;
  }else{
   right--;
  }
}

2 申请一个hashMap key记录数组元素 value数组元素下表 时间复杂度O(n)

for (int i = 0; i < numbers.length; i++) {
        if (map.containsKey(target - numbers[i])) {
            result[1] = i + 1;
            result[0] = map.get(target - numbers[i]);
            return result;
        }
        map.put(numbers[i], i + 1);
    }

 

posted @ 2017-09-28 16:09  WegYcx  阅读(132)  评论(0编辑  收藏  举报