LeetCode Two Sum

本文探讨了在整数数组中寻找两个数使它们的和等于特定目标值的问题。介绍了三种解决方案:直接双层循环、排序加双指针以及哈希表方法。哈希表方法在时间和空间效率上表现最佳。

题目:

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.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

方法1:最直观的复杂度为O(n^2),超时。

方法2:先排序,这样的话就要记下以前的索引,转换用时O(n),排序用时O(nlgn),查找用时O(n)。

struct node {
	int val;
	int idx;
	node(){}
	node(int num, int index): val(num), idx(index) {}
	bool operator < (const node& other) const {
	    return val < other.val;
	}
};

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
    	vector<int> ans(2);
    	vector<node> res(numbers.size());
    	//O(n)
    	for(int i = 0; i < numbers.size(); i++) 
    		res[i] = node(numbers[i], i+1);
        //O(nlgn)
    	sort(res.begin(), res.end());
    	int begin = 0, end = numbers.size()-1;
    	//O(n)
    	while(begin < end) {
    		int tmp = res[begin].val + res[end].val;
    		if(target == tmp) {
    			ans[0] = min(res[begin].idx, res[end].idx);
    			ans[1] = max(res[begin].idx, res[end].idx);
    			break;
    		}
    		else if(target > tmp)
    			begin++;
    		else
    			end--;
    	}
    	return ans;
    }
};

方法3:使用哈希表(利用stl中的unordered_map实现),边建表,边判断,复杂度为最优O(n)。

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
    	vector<int> ans(2); 
    	int len = numbers.size();
    	unordered_map<int, int> hash_table;
    	for(int i = 0; i < len; i++) {
    		//表中存在与它和为target的数 
    		int other = target - numbers[i];
    		if(hash_table.find(other) != hash_table.end()) {
				ans[0] = hash_table[other];
				ans[1] = i+1;
				break;
			}
    		//不在hash表中,加入 
    		if(hash_table.find(numbers[i]) == hash_table.end())
    			hash_table[numbers[i]] = i+1;
    	}
    	return ans;
    }
};





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值