算法题目--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.

Example:

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

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

心路历程:

看到这道题目,自然而然就想到最暴力的方法——二重循环。这种解法大家都会,如果止步于此,那就没有进步。于是就解读了leetcode给出的几种方法,发现可以做的改进还挺多。

解决方案:

1.最直接的方法,是采用二重循环进行遍历,当然是有代价的,时间复杂度为 O ( n2 ),空间复杂度为O(1),好在这道题并没有对运行时间严格控制,该方法行得通。C++实现代码如下:
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) {
		for (int i = 0; i < nums.size(); i++) {       //二重循环
			for (int j = i + 1; j < nums.size(); j++) {
				if (target == nums[i] + nums[j]) {
					vector<int> result;
					result.push_back(i);
					result.push_back(j);
					return result;
				}
			}
		}
	}
};
int main() {
	vector<int> nums;
	nums.push_back(2);
	nums.push_back(7);
	nums.push_back(11);
	nums.push_back(15);
	int target = 9;
	Solution solution;
	vector<int> result = solution.twoSum(nums, target);
	cout << "The first index is " << result[0] << endl;
	cout << "The second index is " << result[1] << endl;
	getchar();
}
2.第二种方法来自leetcode,采用哈希表的方法,节省了一重遍历的时间,时间复杂度为O(n)。同时,哈希表的建立需要空间,使得空间复杂度变为O(n)。在本解中,我们看到了map的强大作用,containsKey方法判断是否存在某个key,get方法返回对应key 的value。Java实现代码如下:
public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        map.put(nums[i], i);
    }
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement) && map.get(complement) != i) {
            return new int[] { i, map.get(complement) };
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}
3.第三种方法来自leetcode,同样采用哈希表的方法。不同的是,在建表的过程不断地“往回看”,一旦发现解,即返回结果。这种方法的复杂度仍与2中相同,但实际中性能应该比2要好。Java实现代码如下:
public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[] { map.get(complement), i };
        }
        map.put(nums[i], i);
    }
    throw new IllegalArgumentException("No two sum solution");
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值