哈希表 Given an array of integers, return indices of the two numbers such that they add up to a specif

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, and you may not use the same element twice.

Example:

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

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

class HashTable {
private:
    int *data;
    int *flag;
    int size, cnt;
private:
    int hash_code(int val) {
        return (val % this->size + this->size) % this->size;
    }
    int has_val(int val) {
        int x = val / 30;
        int y = val % 30;
        return this->flag[x] & (1 << y);
    }
    void set_val(int val) {
        int x = val / 30;
        int y = val % 30;
        this->flag[x] |= (1 << y);
    }
public:
    HashTable(int size) {
        this->size = 2 * size;
        this->data = new int[this->size];
        int flag_size = this->size / 30 + 1;
        this->flag = new int[flag_size];
        this->cnt = 0;
    }
    int insert(int val) {
        int times = 0;
        int hash = hash_code(val);
        while (has_val(hash) && this->data[hash] != val) {
            hash += (++times);
            hash %= this->size;
        }
        if (has_val(hash)) return 0;
        set_val(hash);
        this->data[hash] = val;
        this->cnt++;
        return 1;
    }
    int search(int val) {
        int times = 0;
        int hash = hash_code(val);
        while (has_val(hash) && this->data[hash] != val) {
            hash += (++times);
            hash %= this->size;
        }
        return has_val(hash);
    }
    ~HashTable() {
        delete []this->data;
        delete []this->flag;
    }
};

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        HashTable hash(nums.size());
        vector<int> ret(2);
        for (int i = 0; i < nums.size(); i++) {
            hash.insert(nums[i]);
        }
        int flag = 1;
        for (int i = 0; i < nums.size() && flag; i++) {
            int val = target - nums[i];
            ret.clear();
            if (!hash.search(val)) continue;
            ret.push_back(i);
            for (int j = i + 1; j < nums.size() && flag; j++) {
                if (nums[j] != val) continue;
                ret.push_back(j);
                flag = 0;
            }
        }
        if (flag) ret.clear();
        return ret;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值