您的位置:首页 > 其它

leetcode - TwoSum

2017-09-12 23:31 393 查看
最简单的一道题开始刷题之旅。。。

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

首先暴力算法肯定能解决O(N*N),但是时间满足不了。转化为查找的问题来解决。如求target=9,只对数组遍历一遍,遍历的时候在hashMap中查找target-nums[i],如果没有找到,则将当前的数组元素的下标以及target-nums[i]插入hash表,这样遍历一遍,找到即return。

先是使用c语言手撸一个hashmap,简单的数组实现,开放定址,线性探测法解决冲突。

/**
* Note: The returned array must be malloced, assume caller calls free().
*/
#include <stdio.h>
#include <stdlib.h>

#define NULLVALUE -32768

typedef enum status
{
empty,occupy
}STATUS;
typedef struct hashCell
{
int key;
int pos;
STATUS sts;
}CELL,*PCELL;
typedef struct hashTable
{
int tableSize;
PCELL table;
}HASH,*PHASH;

int hashFunc(int key,PHASH hash)
{
return abs(key)%(hash->tableSize);//绝对值处理负数元素
}

PHASH initHash(int tableSize)
{
PHASH hash = (PHASH)malloc(sizeof(HASH));
if(!hash)return NULL;
hash->tableSize = tableSize;
hash->table = (PCELL)malloc(sizeof(CELL)*tableSize);
if(!hash->table)return NULL;
for(int i=0;i<tableSize;i++)
{
hash->table[i].key = NULLVALUE;
hash->table[i].pos = NULLVALUE;
hash->table[i].sts = empty;
}
return hash;
}

void insertHash(int key,int pos,PHASH hash)
{
int val = hashFunc(key,hash);
while(hash->table[val].sts!=empty)
val = (val+1)%(hash->tableSize);
hash->table[val].key = key;
hash->table[val].pos = pos;
hash->table[val].sts = occupy;
}

PCELL findHash(int key,PHASH hash)
{
int val = hashFunc(key,hash);
while(hash->table[val].key!=key)
{
val = (val+1)%(hash->tableSize);
if(hash->table[val].sts == empty ||(val == hashFunc(key,hash)))
return NULL;
}
return &hash->table[val];
}

int* twoSum(int* nums, int numsSize, int target) {
int tableSize = numsSize*2;
PHASH hash = initHash(tableSize);
PCELL p = NULL;
int *ret = (int*)malloc(sizeof(int)*2);
ret[0] = 0;
ret[1] = 0;
for (int i = 0; i<numsSize; i++)
{
if (p = findHash(nums[i], hash))
{
int *ret = (int*)malloc(sizeof(int) * 2);
ret[0] = p->pos;
ret[1] = i;
free(hash->table);
free(hash);
return ret;
}
else//若没找到nums[i],则将target - nums[i]和i插入hashMap
{
int rem = target - nums[i];
insertHash(rem, i, hash);
}
}
return ret;
}


要注意一点,就是元素为负的时候,取绝对值再进行hash,否则数组访问就出错了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  TwoSum