[leetcode 001]Two Sum
Question:
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Method:
Java
- 1.暴力双循环,时间复杂度为O(n^2)
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 ;}}
- 2.利用HashMap 或者 HashTable,时间复杂度为O(N)
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
以绝大多数人的努力程度之低,根本到不了拼天赋的地步

浙公网安备 33010602011771号