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].
详见:https://leetcode.com/problems/two-sum/description/
给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字。
要求:这个函数twoSum必须要返回能够相加等于目标数字的两个数的索引,且index1必须要小于index2。
Java实现:
暴力解:
class Solution { public int[] twoSum(int[] nums, int target) { int[] res=new int[2]; for(int i=0;i<nums.length;++i){ for(int j=i+1;j<nums.length;++j){ if(nums[i]+nums[j]==target){ res[0]=i; res[1]=j; } } } return res; } }
Map:空间换时间
class Solution { public int[] twoSum(int[] nums, int target) { int[] res=new int[2]; Map<Integer,Integer> map=new HashMap<Integer,Integer>(); for(int i=0;i<nums.length;++i){ if(map.containsKey(target-nums[i])){ res[0]=map.get(target-nums[i]); res[1]=i; return res; } map.put(nums[i],i); } return res; } }
python:
方法一:
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: hash={} for i in range(len(nums)): if target-nums[i] in hash: return hash[target-nums[i]],i else: hash[nums[i]]=i return -1,-1
方法二:
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: for i in range(len(nums)): if target-nums[i] in nums and nums.index(target-nums[i])!=i: return nums.index(target-nums[i]),i return -1,-1
golang:
方法一:
func twoSum(nums []int, target int) []int { for i:=0;i<len(nums);i++{ for j:=i+1;j<len(nums);j++{ if nums[i]+nums[j]==target{ return []int{i,j} } } } return []int{} }
方法二:
func twoSum(nums []int, target int) []int { hash:=make(map[int]int) for i,v:=range nums{ j,ok:=hash[target-v] if ok{ return []int{i,j} } hash[v]=i } return []int{} }