LeetCode刷题日记001——两数之和

LeetCode1——两数之和

题干

	给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。
	你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
	你可以按任意顺序返回答案
示例1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

自己的思路

​ 两层循环,寻找target-nums[i]即可,时间复杂度为O(n^2)

#include <vector>
using namespace std;

class Solution {
    
    
public:
    vector<int> twoSum(vector<int>& nums, int target) {
    
    
        for (int i = 0; i < nums.size()-1; i++) {
    
    
            int left = target - nums[i];
            for (int j = i + 1; j < nums.size(); j++) {
    
    
                if (nums[j] == left) {
    
    
                    return {
    
    i, j};
                }
            }
        }

        return {
    
    };
    }
};

题解的思路

   之所以需要两层循环是因为要寻找target-nums[i],因此可以找一种方法,将其变为一层循环即可搞定。那我们可以考虑使用哈希表,将nums[i]作为键,i作为值存放进哈希表。我们每遍历一个nums的值,就去哈希表中寻找有没有target-nums[i]的值,如果有,那就返回,没有的话就将其添加进哈希表中。时间复杂度为O(n)。具体代码如下:

#include <unordered_map>
using namespace std;

class Solution {
    
    
public:
    vector<int> twoSum(vector<int>& nums, int target) {
    
    
        unordered_map<int, int> hash;

        for (int i = 0; i < nums.size(); i++) {
    
    
            auto it = hash.find(target - nums[i]);
            if (it != hash.end()) {
    
    
                return {
    
    it->second, i};
            }
            hash[nums[i]] = i;
        }

        return {
    
    };
    }
};

测试代码

// #include "solution.cpp"
#include "Answer.cpp"

int main(void) {
    
    
	Solution solution; 
	vector<int> nums = {
    
     3,2,4 };
	int target = 6;

	vector<int> result = solution.twoSum(nums, target);
	printf("%d %d\n", result[0], result[1]);
}

猜你喜欢

转载自blog.csdn.net/qq_43419761/article/details/130202633
今日推荐