码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode 001]Two Sum

时间:2016-05-15 17:59:37      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

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)
  1. publicclassSolution{
  2. publicint[] twoSum(int[] nums,int target){
  3. int[] arr =newint[2];
  4. for(int i =0;i< nums.length-1; i++){
  5. for(int j = i+1; j< nums.length; j++){
  6. if(target == nums[i]+ nums[j]){
  7. arr[0]= i ;
  8. arr[1]= j ;
  9. }
  10. }
  11. }
  12. return arr ;
  13. }
  14. }
  • 2.利用HashMap 或者 HashTable,时间复杂度为O(N)
  1. publicclassSolution{
  2. publicint[] twoSum(int[] nums,int target){
  3. int[] result ={0,0};
  4. Map<Integer,Integer> map =newHashMap<Integer,Integer>();
  5. for(int i =0;i<nums.length;i++){
  6. if(map.containsKey(target-nums[i])){
  7. result[0]= map.get(target-nums[i]);
  8. result[1]= i;
  9. }else{
  10. map.put(nums[i],i);
  11. }
  12. }
  13. return result ;
  14. }
  15. }

思路解析:
明显优于第一种解法,时间复杂度上大大降低
创建一个hash表,将数组的v值和索引值当作hash表的K-V
当存在 target-k存在于表中时,即取出对应的value值,就是所要找的位置


Python
同样的Hashtable思路,key is number,value is index

  1. classSolution(object):
  2. def twoSum(self, nums, target):
  3. """
  4. :type nums: List[int]
  5. :type target: int
  6. :rtype: List[int]
  7. """
  8. index ={};
  9. for i,j in enumerate(nums):
  10. if target-j in index:
  11. return[index[target-j],i]
  12. index[j]= i





[leetcode 001]Two Sum

标签:

原文地址:http://www.cnblogs.com/zhjiann/p/5495491.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!