【Leetcode】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].


思路:

首先循环数组,取出数组中的第一个元素放入到Hashmap中,其中以值为key,坐标为value,是Hashmap结构中的关键。取数组第二个值的时候,根据目标和与当前元素之差,在Hashmap中找相应的差值。如果存在该差值,说明存在两个数之和是目标和。此时记录下当前数组元素下标并拿出Hashmap中数组元素下标即可。若不是,就把该数的数值和数组坐标作为Key-Value放入map中,依次往下推算。Hashmap获取元素的时间复杂度是O(1),所以总的时间复杂度仍不超过O(n)。

注意:

  • 判定是否存在该差值时,要同时判断该差值的下标是不是当前遍历的元素下标,以避免重复

  • 哈希表作为一个Collection,初始化时请注意声明Key和Value的类型

  • 以数组内坐标的值为Key,以数组坐标为Value,通过数值的比较,取key值

Java版本:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<Integer,Integer>();
        for(int i = 0; i < nums.length; i++){
            int x = nums[i];
            if(map.containsKey(target - x)){
                return new int[]{map.get(target - x), i};
            }
            map.put(x, i);
        }
        return new int[]{0,0};
    }
}


Python版本:

class Solution:
    def twoSum(self, nums, target):
        if len(nums) <= 1:
            return False
        buff_dict = {}
        for i in range(len(nums)):
            if nums[i] in buff_dict:
                return [buff_dict[nums[i]], i]
            else:
                buff_dict[target - nums[i]] = i

Python则是主要合理利用字典型,通过将target值依次减去数组中的数值,获得的值存入到buff_dict字典中,然后通过差值与字典中的值做比较。

与Java版本的不同时,Java用的Map存储的是数组值和坐标,然后用target-nums[i] 差值匹配Map集合中之前的值。而Python版本则是用字典型存储差值 target-nums[i] 和当前数组的坐标,然后用数组值与差值匹配。

C++版本:

vector<int> twoSum(vector<int> &numbers, int target)
{
    //Key is the number and value is its index in the vector.
	unordered_map<int, int> hash;
	vector<int> result;
	for (int i = 0; i < numbers.size(); i++) {
		int numberToFind = target - numbers[i];

            //if numberToFind is found in map, return them
		if (hash.find(numberToFind) != hash.end()) {
                    //+1 because indices are NOT zero based
			result.push_back(hash[numberToFind] + 1);
			result.push_back(i + 1);			
			return result;
		}

            //number was not found. Put it in the map.
		hash[numbers[i]] = i;
	}
	return result;
思路大体相似,主要是用到了Vector这个数据类型。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值