p2 两数之和 (leetcode1)

一:解题思路

这道题有2种解题方法,第一种:用2重for循环遍历数组,进而确定下标。时间复杂度为O(n^2),空间复杂度为O(1)。第二种:利用一个哈希表来存放已经访问过得数组中的元素,当再次访问数组的元素的时候,这个时候就在哈希表中去找需要的目标元素。第二种方法由于只遍历了数组一遍,所以时间复杂度为O(n),由于使用了一个哈希表所以空间复杂度为O(n)。

二:完整代码示例 (C++版和Java版)

方法一:

C++98/03代码如下:

Time:O(n^2),Space:O(1)

class Solution 
{
public:
    vector<int> twoSum(vector<int>& nums, int target) 
    {
        vector<int> ret(2,-1);

        for (int i = 0; i < nums.size(); i++)
        {
            for (int j = i + 1; j < nums.size(); j++)
            {
                if (nums[i] + nums[j] == target)
                {
                    ret[0]=i;
                    ret[1]=j;
                }
            }
        }

        return ret;
    }
};
C++11代码如下:

#include <iostream>
#include <vector>

using namespace std;

class Solution
{
public:
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int> ret = {-1,-1};

for (int i = 0; i < nums.size(); i++)
{
for (int j = i + 1; j < nums.size(); j++)
{
if (nums[i] + nums[j] == target)
{
ret = {i,j};
}
}
}

return ret;
}
};

Java代码如下:

第二种解法:

C++98/03

class Solution 
{
public:
    vector<int> twoSum(vector<int>& nums, int target) 
    {
        vector<int> ret(2, -1);
        map<int,int> hash_map;

        for (int i = 0; i < nums.size(); i++)
        {
            int another = target - nums[i];

            if (hash_map.count(another))
            {
                ret[0] = hash_map[another];
                ret[1] = i;
                break;
            }

            hash_map[nums[i]] = i;
        }

        return ret;
    }
};
C++11
class Solution 
{
public:
    vector<int> twoSum(vector<int>& nums, int target) 
    {
        vector<int> ret = {-1,-1};
        unordered_map<int, int> hash_map;
        
        for(int i=0;i<nums.size();i++)
        {
            int another=target-nums[i];

            if(hash_map.count(another))
            {
                ret={hash_map[another],i};
            }

            hash_map[nums[i]]=i;
        }

        return ret;
    }
};

猜你喜欢

转载自www.cnblogs.com/repinkply/p/12421253.html
今日推荐