1. Two Sum
题目描述:
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].
解题思路:
根据题目的大意就是从给定的一个整数数组中,找到相加等于target的两个数组下标
第一种方法:
看到这道题目的第一想法就是先把数组排序(凡是把乱序变成有序总是帮助的),然后维护两个指针一个从前往后移动,一个从后往前移动,将两个索引指向的元素相加,和target对比,大于target后面的指针向前移动,小于target前面的指针向后移动,直到相加等于target。获得两个数值,然后根据数值去原来的数组中寻找索引,最后返回。
注意点:
1、要记得维护两个数组,因为题目要求的是返回原数组的元素的下标,排序之后元素顺序就乱了
2、根据元素的值寻找原数组的下标的时候要注意,考虑出现相同的值怎么办,也就是说target是10 两个元素都是5,这样子判断的时候,记得要做一个互斥的操作,就是判断寻找第二个元素的时候加上判断寻找到的下标是否和第一个寻找到的下标相等。
这个方法比较简单,瓶颈在于排序算法的时间复杂度,不贴代码了。
第二种方法:
我们可以使用一个map,里面的key是元素本身,value是元素下标,遍历数组拿到元素elements,首先从map之中获取一下target-elements是否为空,为空就把当前value和key加入map,非空直接返回map得到的元素和当前的下标,这种方法的时间复杂度为O(n);
代码如下:
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++)
{
if (map.get(target - nums[i]) != null)
{
return new int[] {map.get(target - nums[i]), i};
}
else
{
map.put(nums[i], i);
}
}
return null;
}
}