1. 两数之和

2018-09-18  本文已影响0人  HITZGD

1、暴力法,求target-num[current]是否满足

class Solution {
public:
    std::vector<int> twoSum(std::vector<int>& nums, int target) {
        std::vector<int> result;
        bool breakFlag = false;
        for (int i = 0; i < nums.size(); i ++)
        {
            for (int j = i +1; j < nums.size(); j ++)
            {
                if (target - nums[j] == nums[i])
                {
                    result.push_back(i);
                    result.push_back(j);
                    breakFlag = true;
                    break;
                }
            }
            if (breakFlag) breakFlag;
        }
        return result;
    }
};

2、哈希表

    std::vector<int> twoSum2(std::vector<int>& nums, int target)
    {
        std::vector<int> result;
        std::unordered_map<int, int> hash;
        for (int i = 0; i < nums.size(); i ++)
        {
            if(hash.find(target - nums[i]) != hash.end())
            {
                result.push_back(hash[target - nums[i]]);
                result.push_back(i);
                break;
            }
            hash.insert({ nums[i], i });
        }
        return  result;
    }
上一篇 下一篇

猜你喜欢

热点阅读