标签:
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.
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Java
publicclassSolution{publicint[] twoSum(int[] nums,int target){int[] arr =newint[2];for(int i =0;i< nums.length-1; i++){for(int j = i+1; j< nums.length; j++){if(target == nums[i]+ nums[j]){ arr[0]= i ; arr[1]= j ;}}}return arr ;}}publicclassSolution{publicint[] twoSum(int[] nums,int target){int[] result ={0,0};Map<Integer,Integer> map =newHashMap<Integer,Integer>();for(int i =0;i<nums.length;i++){if(map.containsKey(target-nums[i])){ result[0]= map.get(target-nums[i]); result[1]= i;}else{ map.put(nums[i],i);}}return result ;}}思路解析:
明显优于第一种解法,时间复杂度上大大降低
创建一个hash表,将数组的v值和索引值当作hash表的K-V
当存在 target-k存在于表中时,即取出对应的value值,就是所要找的位置
Python
同样的Hashtable思路,key is number,value is index
classSolution(object):def twoSum(self, nums, target):""" :type nums: List[int] :type target: int :rtype: List[int] """ index ={};for i,j in enumerate(nums):if target-j in index:return[index[target-j],i] index[j]= i标签:
原文地址:http://www.cnblogs.com/zhjiann/p/5495491.html