1. Two Sum

Question:
Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Solution 1 (brute force)
就是最簡單一個一個加過去,用兩個for循環,時間複雜度爲o(n^2)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int n =nums.size();
        vector<int> arr;  //存儲和爲target的下標
        int k=0;//用來計數
        for(int i=0;i<n;i++)
        {
            for(int j=i+1;j<n;j++)
            {
                if(nums[i]+nums[j]==target)
                {
                    arr.push_back(i);
                    arr.push_back(j);
                }
                    
            }
        }
        return arr;
    }
};

solution2 (hashmap)
這個解法最令我生氣的是,好不容易我邁出了把hashmap從理論去實踐這一步,但是hashmap卻過時了???
呵呵呵呵
變成了unordered_map,unordered_map是key,value形式,但是內部是用哈希表實現的,和map不一樣,map是用紅黑樹實現的

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map <int,int> mp;
        //vector<int> ret;
        for(int i=0;i<nums.size();i++)
        {
            if(mp.find(target-nums[i])!=mp.end())
            {
                return {mp[target-nums[i]],i};
                //ret.push_back(i);
                //ret.push_back(mp[target-nums[i]]);
            }       
            //mp.insert(pair<int,int>(i,nums[i]));
            mp[nums[i]] = i;
        }
        //return ret;
        return { };
    }
};

只用一個unorder_map的話就是查找有沒有,然後把數據放入mp,不理解的是mp.insert(pair<int,int>(i,nums[i]));這種插入方式會報錯,明明這種方式也是合理的。
註釋部分是用一個vector的數組來存儲符合要求的下標,然後返回數組。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章