leetcode刷题:Two Sum

问题描述hash Array

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


c语言解决
由于这个问题有时间上的限制,我一开始想到的是用双重循环,外循环num2=target-nums[i],然后再内循环从i+1一直找到数组的尾部寻找有没有num2 的存在,这样的时间复杂度是n^2,没有被AC。

然后我看到题目的标签提示是hash,就去网上学了一下hash.
哈希表是基于快速存取设计的,是典型的空间换时间,此数据结构可以理解为一个线性表,但其中的元素不是紧密排列的,存在空隙。哈希表是根据关键值直接进行访问的数据结构。是通过将关键值映射到表中一个位置进行访问,加快查找速度。所以做题思路就是先根据nums[]构建一个哈希表,然后再哈希表中查找num2.
构建哈希表的复杂度是n,查找的复杂度是1.

int* twoSum(int* nums, int numsSize, int target) {

    int i=0,num1,num2;
    int hashAddress1,hashAddress2;
    int hashlength=102400;
    int hash[102400];
    //将数组的所有元素初始化为-1.
    memset(hash,-1,sizeof(hash));
    int *p;
    p = (int*)malloc(2*sizeof(int));

    //判断输入的数组不为空且多于一个元素
    if(nums==NULL||numsSize<2){
        return NULL;
    }
    //构建哈希表
    for(i=0;i<numsSize;i++){

        hashAddress1 = abs(nums[i]) % hashlength;
        //如果产生了冲突,就用线性探测法来解决
        while(hash[hashAddress1]!=-1){
            hashAddress1 = (++hashAddress1) % hashlength;
        }
        hash[hashAddress1] = i;
    }
    //查找哈希表
    i=0;
    while(i<numsSize){
        num1=nums[i];
        num2=target-nums[i];
        hashAddress2 =abs(num2) % hashlength;
        while((hash[hashAddress2]!=-1 && nums[hash[hashAddress2]]!=num2)||(i==hash[hashAddress2])){
            hashAddress2 = (++hashAddress2) % hashlength; 
        }
        if(hash[hashAddress2]==-1)
        {
            i++;
            continue;
        }
        if(hash[hashAddress2]>i){
            p[0]=i+1;
            p[1]=hash[hashAddress2]+1;
            break;
        }
    }
    return p;
}

java版
java中有map接口,真是太好用了。用HashMap来实现。用HashMap来存储数组中的值和index.HashMap中查询键值对的开销是固定的,因此在性能上得到很大的提升。
该题中应用数组的值来做index索引来检索index。

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        //声明哈希表
        Map map = new HashMap();
        int[] res = new int[2];
        //创建哈希表
        for(int i = 0;i<nums.length;i++){
            map.put(nums[i], i);
        }
        //查找哈希表,注意得到的index1不能等于index2
        for(int i = 0;i<nums.length;i++){
            int numb = target - nums[i];
            if(map.get(numb)!=null && (int)map.get(numb)!=i ){
                res[0] = i + 1;
                res[1] = (int)map.get(numb)+1;
                break;
            }
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值