leetcode-1-两数之和(三种方法)

#include<vector>
#include<map>
#include<iostream>
using namespace std;

/*暴力遍历
vector<int> twoSum(vector<int>& nums, int target) {
    vector<int> ret;
    if(nums.size()<2)
        return ret;
    for(int i = 0;i<nums.size()-1;i++)
    {
        for(int j = i+1;j<nums.size();j++)
        {
            if(nums[i]+nums[j]==target)
            {
                ret.push_back(i);
                ret.push_back(j);
            }
        }
    }
    return ret;
}
    */
    /*两遍哈希表
vector<int> twoSum(vector<int>& nums, int target) {
    vector<int> vi;
    map<int,int> hashmap;
    pair<map<int,int>::iterator,bool> insertpair;//判断插入成功与否
    for(int i = 0;i<nums.size();i++){
        //hashmap.insert(pair<int,int>(nums[i],i));
        insertpair = hashmap.insert(map<int,int>::value_type(nums[i],i));
        if(insertpair.second==false)
        {//插入失败,判断当前数是否为target的一半
            if(nums[i]*2==target){
                vi.push_back(insertpair.first->second);
                vi.push_back(i);
                return vi;
            }
        }
    }
    int den;
    for(int i = 0;i<nums.size();i++){
        den = target - nums[i];
        auto iter = hashmap.find(den);
        if(iter!=hashmap.end()&&iter->second!=i)
        {
            vi.push_back(i);
            vi.push_back(iter->second);
            return vi;
        }
    }
    return vi;
}
    */
    //一次遍历哈希
vector<int> twoSum(vector<int>& nums, int target) {
    vector<int> vi;
    map<int, int> hashmap;
    pair<map<int, int>::iterator, bool> insertpair;//判断插入成功与否
    for (int i = 0; i < nums.size(); i++) {
        //hashmap.insert(pair<int,int>(nums[i],i));
        insertpair = hashmap.insert(map<int, int>::value_type(nums[i], i));
        if (insertpair.second == false)
        {//插入失败,判断当前数是否为target的一半
            if (nums[i] * 2 == target) {
                vi.push_back(insertpair.first->second);
                vi.push_back(i);
                return vi;
            }
        }
        else {//如果插入成功,判断另一个数是否在hash表中
            auto iter = hashmap.find(target - nums[i]);
            if (iter != hashmap.end()) {
                if (iter->second != i)
                {
                    vi.push_back(iter->second);
                    vi.push_back(i);
                    return vi;
                }

            }
        }
    }
    return vi;
}

int main()
{
    vector<int> vi1({3,3});
    vector<int> vi2({1,7,4,8,13});
    vector<int> ret;
    ret = twoSum(vi1, 6);
    for (auto i : ret)
        cout << i << "\t";
    cout << endl;
    ret = twoSum(vi2, 15);
    for (auto i : ret)
        cout << i << "\t";
    cout << endl;
}
posted @ 2020-09-16 13:09  shadowgully  阅读(118)  评论(0编辑  收藏  举报