哈希表 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;
    }
};

你可能感兴趣的:(数据结构与算法)