描述

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

 

代码

暴力,时间复杂度为 O(N^2)

public int[] twoSum(int[] numbers, int target) {
int[] res = new int[2];
for (int i = 0; i < numbers.length - 1; i++) {
  if (numbers[i] <= target) {
    for (int j = i + 1; j < numbers.length; j++) {
      if (target - numbers[i] == numbers[j]) {
        res[0] = i + 1;
        res[1] = j + 1;
      }
    }
  }
}
return res;
}

散列表hasmMap

/**
* 用 HashMap 存储数组元素和索引的映射,在访问到 nums[i] 时,判断 HashMap 中是否存在 target - nums[i]
* 如果存在说明 target - nums[i] 所在的索引和 i 就是要找的两个数。
* 该方法的时间复杂度为 O(N),空间复杂度为 O(N),使用空间来换取时间。
* @param nums
* @param target
* @return
*/
public int[] twoSum_2(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
  if (map.containsKey(target - nums[i])) {
    return new int[] { map.get(target - nums[i]) + 1, i + 1 };
  } else {
    map.put(nums[i], i);
  }
}
return null;
}

先排序,首尾指针

xx

posted on 2018-05-08 15:35  反光的小鱼儿  阅读(135)  评论(0编辑  收藏  举报