Leetcode #1 Two Sum

LEETCODE #1

问题描述

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].

0、背景

来源Leetcode题库Algorithms part,难度定级Easy。
参考Grandyang博客:Two Sum 两数之和,语言选用C++,Java和Python。

1、算法

给定一个序列Nums,一个Target,目标寻找一对数字,使其和为Target,给出目标的下标对。
限制条件:
1、目标一定存在,并且唯一
2、数字只能选用最多一次

a.枚举

两重循环,筛选所有可能,找到结果直接break。
时间复杂度:O(n^2),我没有尝试,Grandyang提交结果返回TimeLimitExceeded。

b.Hash

枚举问题在于盲目寻找结果,没有考虑和为Target的特点,利用Hash可以快速查找目标结果。
方法:Hash[number] = index
对Array进行标记,数值对应相应的下标,枚举第一个数的下标,检查Hash[Target-number_1]是否存在,即可判断结果。1
时间复杂度:O(n),可以通过测试,由于需要筛选所有数字才能得到结果,线性复杂度已经是最好的方法。

2、实现

a.CPP

使用unordered_map类array实现Hash功能,index容器记录结果。
拓展:STL库中unordered_map类底层通过哈希表实现,通过Hash值遍历,结果是无序的,而map类底层实现方式是红黑树,源码包含operate操作比较元素大小,遍历结果是有序的,从时间效率和内存占用来看,unordered_map都要优于map,并且在查找效率上往往是O(1),如果数据必须有序,使用map。
具体的内容需要查阅《STL源码剖析》,以下几篇博客可作为简单参考:
STL库unordered_map和map的性能测试参考hnlylyb博客:STL中map和unordered_map选择
map类源码解析参考LLTX_博客:【STL】从源码看map
unordered类源码解析参考:C++ unordered_map Reference

// cpp version
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
       unordered_map<int,int> array;
       vector<int> index;
        for (int i = 0; i < nums.size(); i++)
        {
            array[nums[i]] = i;
        }
        for (int i = 0; i < nums.size(); i++)
        {
            int tmp = target - nums[i];
            if (array.count(tmp) && array[tmp] != i)
            {
                index.push_back(i);
                index.push_back(array[tmp]);
                break;
            }
        }
        return index;
    }
};

b.Java

Java使用HashMap实现类似unordered_map的操作。
HashMap源码参考 是没有名字 的博客:Hashmap源码

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> array = new HashMap<Integer,Integer>();
        int[] index = new int[2];
        for (int i = 0; i < nums.length; i ++)
        {
            array.put(nums[i],i);
        }
        for (int i = 0; i < nums.length; i ++)
        {
            int temp = target - nums[i];
            if (array.containsKey(temp) && array.get(temp) != i)
            {
                index[0] = i;
                index[1] = array.get(temp);
                break;
            }
        }
        return index;
    }
}

c.Python

留待以后补充。

3、相关

想到以后补充。


  1. 因为解唯一,所以即使原数据存在相同数字,相同数字不会出现在结果中。 ↩︎

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值