leetcode刷题笔记——1.两数之和

题目描述

在这里插入图片描述

分析

暴力枚举

描述

对数组每个元素x,遍历寻找元素target-x。并注意到在遍历时,当前元素已与位于其之前的元素匹配过,于是只需要在其之后的元素中查找即可。

代码

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    for(int i = 0; i < numsSize; i++){
        for(int j = i+1; j < numsSize; j++){
            if(nums[i] + nums[j] == target){
                int *ret=(int*)malloc(sizeof(int)*2);
                ret[0]=i;
                ret[1]=j;
                *returnSize=2;
                return ret;
            }
        }
    }
    *returnSize=0;
    return NULL;
}

哈希表

描述

利用哈希表查找的时间复杂度近似为O(1)可以设计时间复杂度为O(N)的算法

代码

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
struct hashList{
    int id;
    int val;
    UT_hash_handle hh;
};
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
	struct hashList *set = NULL;
    int i;
    for(i = 0; i < numsSize; i++){
        struct hashList *tmp;
        int cor = target-nums[i];
        HASH_FIND_INT(set,&cor,tmp);
        if(tmp == NULL){
            tmp = malloc(sizeof(struct hashList));
            tmp->id = nums[i];
            tmp->val = i;
            HASH_ADD_INT(set,id,tmp);
        }
        else{
            int *ret = (int *)malloc(sizeof(int)*2);
            ret[0] = i;
            ret[1] = tmp->val;
           	*returnSize = 2;
            return ret;
        }
    }
    *returnSize = 0;
    return NULL;
}

收获

哈希表

对于uthash的使用又更加熟练了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值