Problem:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
Solution:
O(n2) runtime, O(1) space – Brute force:
The brute force approach is simple. Loop through each element x and find if there is another value that equals to target – x. As finding another value requires looping through the rest of array, its runtime complexity is O(n2).
O(n) runtime, O(n) space – Hash table:
We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.
Cancel rating
1
2
3
4
5
Average Rating: 4.5 (874 votes)
Is this solution helpful? Read our book to learn more.
题目大意:
给定一个数组和一个目标整数,求在数组中的两个和为目标函数的下标,第一个下标要小于第二个下标(确保有且只有一个结果)
解题思路:
两种方法,一种是暴力破解,找到一个数之后在数组中找target减去这个数的数,时间复杂度O(n^2),效率太低,TLE
第二种方法采用可以经常想到的Hash来解决(本文就是用这种方法),Hash存储与查找
另想到的方法有二叉搜索树和二叉平衡树,B树,不过没有代码实现,不知道对不对。
下面是C语言,C++,Java和Python的解题代码,欢迎批评指正。
Java源代码:
import java.util.*; public class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i=0;i<nums.length;i++){ if(map.containsKey(target-nums[i])){ int[] index={map.get(target-nums[i]),i+1}; return index; } map.put(nums[i],i+1); } return null; } }
C语言源代码(C代码由于自己实现了Map,所以代码比较长):
#include<stdio.h> #include<stdlib.h> #define HASH_SIZE 10000 struct node{ int value; int key; struct node* next; }; struct node* data[HASH_SIZE]; int contains(int key){ int hash = abs(key)%HASH_SIZE; struct node* p = data[hash]; while(p!=NULL){ if(p->key==key)return 1; p=p->next; } return 0; } void put(int key,int value){ int hash = abs(key)%HASH_SIZE; struct node* p = data[hash]; struct node* s = (struct node*)malloc(sizeof(struct node)); s->key=key; s->value=value; s->next=NULL; if(p==NULL){ data[hash] = s; return; } while(p->next!=NULL){ p=p->next; } p->next=s; } int get(int key){ int hash = abs(key)%HASH_SIZE; struct node* p = data[hash]; while(p!=NULL){ if(p->key==key)return p->value; p=p->next; } return 0; } int abs(int value){ return value>0?value:-value; } int* twoSum(int* nums, int numsSize, int target) { int* res = (int*)malloc(sizeof(int)*2); int value; for(value=0;value<HASH_SIZE;value++){ data[value]=NULL; } for(int i=0;i<numsSize;i++){ if(contains(target-nums[i])){ value = get(target-nums[i]); res[0]=value; res[1]=i+1; return res; } put(nums[i],i+1); } return res; }
C++源代码(采用STL的map):
#include<iostream> #include<vector> #include<map> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { map<int,int> map; for(int i=0;i<nums.size();i++){ std::map<int, int>::iterator iter; iter = map.find(target-nums[i]); if(iter!=map.end()){ vector<int> vec; vec.push_back(iter->second); vec.push_back(i+1); return vec; } map[nums[i]]=i+1; } return vector<int>(); } };
Python源代码(不得不说Python代码量就是少啊,爽):
class Solution: # @param {integer[]} nums # @param {integer} target # @return {integer[]} def twoSum(self, nums, target): map={}; for i in range(0,len(nums)): if map.has_key(target-nums[i]): return map[target-nums[i]],i+1 map[nums[i]]=i+1 return 0,0