1. 两数之和
https://leetcode-cn.com/problems/two-sum/
1. 暴力法:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int i, j;
int *result = (int *)malloc(2 * sizeof(int));
for (i = 1; i < numsSize; i++)
{
for (j = 0; j < i; j++)
{
if (target - nums[i] == nums[j])
{
result[0] = j;
result[1] = i;
*returnSize = 2;
*returnSize = 2;
return result;
}
}
}
return NULL;
}
执行用时: 76ms
内存消耗: 6.2MB
2. hash法
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
#define SIZE 2000
#define TWO 2
int hash_tab[SIZE] = {0};
int hash_get_key(int val)
{
int key;
key = val % SIZE;
if (key < 0)
{
key = key + SIZE;
}
return key;
}
int* twoSum(int* nums, int numsSize, int target, int* returnSize)
{
int *retnum = (int *)malloc(TWO * sizeof(int));
for (int i = 0; i < SIZE; i++)
{
hash_tab[i] = INT_MAX;
}
for (int i = 0; i < numsSize; i++)
{
if (hash_tab[hash_get_key(nums[i])] != INT_MAX)
{
retnum[1] = i;
retnum[0] = hash_tab[hash_get_key(nums[i])];
*returnSize = 2;
return retnum;
}
else
{
hash_tab[hash_get_key(target - nums[i])] = i;
}
}
return NULL;
}
执行用时: 4ms
内存消耗: 6.4MB