leetcode 第一题:两数之和-C语言实现

题目地址
题目解析地址

暴力破解:

//暴力破解
int* twoSum1(int* nums, int numsSize, int target, int* returnSize) {
	int i, j;

	for (i = 0; i < numsSize - 1; i++) {
		for (j = i + 1; j < numsSize; j++) {
			if ((nums[i] + nums[j]) == target) {
				int* result = malloc(sizeof(int) * 2);
				if (result != NULL)
				{
					result[0] = i;
					result[1] = j;

					*returnSize = 2;
					return result;
				}
			}
		}
	}

	*returnSize = 0;
	return NULL;
}

hash 表

使用hash表的特性,用内存换时间
所使用的 hash 表库地址如下,使用时,直接copy对应的头文件到项目中即可
uthash

#include<stdio.h>
#include "uthash.h"

struct myHashTable {
	int key;
	int val;
	UT_hash_handle hh;
};

typedef struct myHashTable hashtableT;
typedef struct myHashTable* hashtablePtr;

// hash 表的表头
hashtablePtr hashTableHead;

/*
*  从hash表中查找对应的key是否存在
*/
hashtablePtr find(int key) {
	struct myHashTable* result;
	// 注意这里有个陷阱,使用的是key的地址,不明白为啥??
	HASH_FIND_INT(hashTableHead, &key, result);
	return result;
}

/*
*  将对应的key value 添加到 hash表中
*/
void add(int key, int value) {
	// 查找key 是否已经存在,存在则更新value值,不存在这创建一个节点,并且插入到hash表中
	hashtablePtr it = find(key);
	if (it == NULL) {
		hashtablePtr tmp = malloc(sizeof(hashtableT));
		tmp->key = key;
		tmp->val = value;
		HASH_ADD_INT(hashTableHead, key, tmp);
	} else {
		it->val = value;
	}
}

int* twoSum2(int* nums, int numsSize, int target, int* returnSize) {
	hashTableHead = NULL;
	int i;
	for (i = 0; i < numsSize; i++)
	{
		hashtablePtr it = find(target - nums[i]);
		if (it != NULL) {
			int* result = malloc(sizeof(int) * 2);
			if (result != NULL) {
				result[0] = i;
				result[1] = it->val;
				*returnSize = 2;
				return result;
			}
		}

		add(nums[i], i);
	}

	*returnSize = 0;
	return NULL;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值