原题网址:https://leetcode.com/problems/two-sum/
题目大意:给定一个整数的数组,返回两个数的下标,使得这两个数的加和等于target。
解题思路:
1、暴力法求解
遍历数组,两两相加,时间复杂度为O(
n2
),空间复杂度为O(1)
2、使用Hash表,时间复杂度为O(n),空间复杂度为O(n)
具体代码:
Java实现,主要使用HashMap,散列映射表
public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++){
int x=nums[i];
if(map.containsKey(target-x)){
return new int[] {map.get(target-x),i};
}
map.put(x,i);
}
throw new IllegalArgumentException("No two Sum solution");
}
}
Python实现
这里主要使用Python的字典
class Solution(object):
def twoSum(self, nums, target):
dict = {}
for i in xrange(len(nums)):
x = nums[i]
if target-x in dict:
return (dict[target-x], i)
dict[x] = i