LeetCode 1. Two Sum(给定和,求数对)

题目描述:

    Given an array of integers, return indices of the two numbers such that they add up to a specific target.
    You may assume that each input would have exactly one solution, and you may not use the same element twice.

例子:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


分析:

   题意:给定一个至少包含两个元素的数组,一个目标值,找到两个数,使得他们的和等于目标值,并返回两个数的下标。假设有且只有一组解。 
   思路一:遍历两次数组,找到对应解,时间复杂度为O(n²)。
  思路二:使用C++ map,其中保存对应key值为数组的元素,对应value值为元素下标。现在考察nums[i]:①如果m[nums[i]]和m[target-nums[i]]都没存在,那么nums[i]加入map中;②如果m[nums[i]]存在,m[target-nums[i]]不存在,说明前者找不到配对,跳过不做处理;如果m[target-nums[i]]存在,那么现在有nums[i],完成配对、找到答案,保存对应下标返回即可。时间复杂度为O(n)。


代码:

#include <bits/stdc++.h>

using namespace std;

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int n = nums.size();
		map<int, int> m;
		vector<int> ans(2, 0);
		for(int i = 0; i <= n - 1; i++){
			if(!m.count(nums[i]) && !m.count(target - nums[i])){
				m[nums[i]] = i;
			}
			else if(m.count(nums[i]) && !m.count(target - nums[i])){
				continue;
			}
			else if(m.count(target - nums[i])){
				// debug
				// cout << target - nums[i] << ", " << nums[i] << endl;
				ans[0] = m[target - nums[i]];
				ans[1] = i;
				break;
			}
		}
		return ans;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值