讨论/《哈希表》 - 两数之和/
《哈希表》 - 两数之和
共 4 个回复
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        //创建哈希映射
        unordered_map<int, int> hashmap;
        //数组长度
        int size = nums.size();
        for(int i = 0; i < size; ++i){
            if(hashmap.find(target - nums[i]) != hashmap.end()){
                return {i, hashmap[target - nums[i]]};
            }
            else{
                hashmap[nums[i]] = i;
            }
        }
        return{-1,-1};
    }
};
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int,int> hashlist;
        for(int i=0;i<nums.size();i++){
            if(hashlist.count(target-nums[i])>0){
                return {hashlist[target-nums[i]],i};
            }
            hashlist.insert(make_pair(nums[i],i));
        }
        return {};
    }
};

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> hashmap;
int len=nums.size();
int i,j;
for(i=0;i<len;i++){
int x=nums[i];
auto it=hashmap.find(target-x);
if(it!=hashmap.end())
return {i,it->second};
hashmap.insert(make_pair(x,i));

    }
    return {};
}

};

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
typedef struct {
    int key;
    int index;
    UT_hash_handle hh;
}HashTable;

HashTable *g_users;

void DelHashTable()
{
    HashTable *tmp = NULL;
    HashTable *s = NULL;
    HASH_ITER(hh, g_users, s, tmp) {
        HASH_DEL(g_users, s);
        free(s);
    }
}

int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    g_users = NULL;
    for (int i = 0; i < numsSize; i++) {
        int val = target - nums[i];
        HashTable *cur = NULL;
        HASH_FIND_INT(g_users, &val, cur);
        if (cur != NULL) {
            /* 找到了 */
            int *rslt = (int *)malloc(sizeof(int) * 2);
            rslt[0] = i;
            rslt[1] = cur->index;
            *returnSize = 2;
            DelHashTable();
            return rslt;
        }
        cur = (HashTable *)malloc(sizeof(HashTable));
        cur->key = *(nums + i);
        cur->index = i;
        HASH_ADD_INT(g_users, key, cur);
    }
    *returnSize = 0;
    DelHashTable();
    return NULL;
}