您的位置:首页 > 理论基础 > 数据结构算法

1,Two sum (Hashtable Array)

2015-09-26 18:12 405 查看
/*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

*/

#include<stdlib.h>
#include<stdio.h>

方法一: brute-force
//时间复杂度是O(n^2)太大 ,大数据量会出现 Time Limit Exceeded
int* twoSum1(int * nums, int numsSize , int target) {
int i, j;
for (i = 0; i<numsSize ; i++){
for (j = i + 1; j<numsSize ; j++){
if ((nums [i] + nums[j]) == target){
int* index = (int *)malloc(sizeof( int)* 2);
if (i<j){

index[0] = i + 1;
index[1] = j + 1;
}
else{
index[0] = j + 1;
index[1] = i + 1;
}
return index;

}
}
}
return NULL ;
}

方法二,下面使用java的HashMap数据结构,时间复杂度O(n),空间复杂度是O(n)

public int [] twoSum(int[] nums, int target) {
if(nums == null || nums.length <= 0){
return null ;
}

HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
int len = nums.length ;

for(int i=0; i<len; i++){
int firstNum = nums[i];
int secondNum = target-firstNum;

Integer result = map.get(secondNum);

if(result != null){
int arr[] = new int[2];
if(result > i){
arr[0] = i+1;
arr[1] = result+1;
} else{
arr[0] = result+1;
arr[1] = i+1;
}

return arr;
}

map.put(firstNum, i);

}
return null ;
}

方法三:使用C语言对HashMap进行模仿
typedef struct MapNode{
int key;
int value;
struct MapNode * next;
}MapNode;

void put(MapNode *map, int key , int value, int len ){
int index = key %   len;

MapNode* node = (MapNode *)malloc(sizeof( MapNode));
node->key = key;
node->value = value;

if (map [index].next == NULL){
node->next = NULL;
}
else{
node->next = map[index].next;
}

map[index].next = node;
}

int get(MapNode *map, int key , int len){
int index = key %   len;
MapNode* node = map [index].next;

while (node != NULL ){
if (node->key == key ){
return node->value;
}

node = node->next;
}

return           -999;
}

int* twoSum(int * nums, int numsSize , int target){
if (nums == NULL || numsSize <= 0){
return NULL ;
}

MapNode *map = (MapNode *)malloc(sizeof( MapNode)*numsSize );
for (int i = 0; i < numsSize; i++){
map[i].next = NULL;
}

for (int i = 0; i < numsSize; i++){
int firstNumber = nums [i];
int secondNumber = target - firstNumber;

int result = get(map, secondNumber, numsSize);

if (result != -999){
int* arr = (int *)malloc(sizeof( int)* 2);

if (i >result){
arr[0] = result + 1;
arr[1] = i + 1;
}
else{
arr[0] = i + 1;
arr[1] = result + 1;
}

return arr;
}

put(map, firstNumber, i, numsSize);
}

return NULL ;
}

int main(){

int array[4] = {0,4,3,0};
int *result = twoSum(array, 4, 0);
printf( "[%d ,%d]\n", *result, *(result + 1));

printf( "Hello world \n");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息