搁置
1. 两数之和
暴力枚举
1#include <stdio.h>
2#include <stdlib.h>
3
4int* twoSumNormal(int* nums, int numsSize, int target, int* returnSize);
5
6
7int main(){
8 int nums[4] = [2,7,11,15];
9 int target = 9;
10 int* returnSize = 0;
11 int* res = twoSumNormal(nums, 4, target, returnSize);
12 free(res);
13 return 0;
14}
15
16
17//示例 1:
18//
19//输入:nums = [2,7,11,15], target = 9
20//输出:[0,1]
21//解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
22//示例 2:
23//
24//输入:nums = [3,2,4], target = 6
25//输出:[1,2]
26//示例 3:
27//
28//输入:nums = [3,3], target = 6
29//输出:[0,1]
30
31/**
32 * Note: The returned array must be malloced, assume caller calls free().
33 */
34int* twoSumNormal(int* nums, int numsSize, int target, int* returnSize) {
35 for (int i = 0; i < numsSize; i++) {
36 for (int j = i + 1; j < numsSize; ++j) {
37 if(nums[i] + nums[j] == target){
38 int* res = malloc(sizeof(int) * 2);
39 res[0] = i;
40 res[1] = j;
41 *returnSize = 2;
42 return res;
43 }
44 }
45 }
46
47 *returnSize = 0;
48 return NULL;
49}
50
哈希表
关于uthash.h
1#include "stdio.h"
2#include "stdlib.h"
3#include "uthash.h"
4
5//单个节点
6struct hashTable {
7 int key;
8 int val;
9 UT_hash_handle hh;
10};
11
12
13struct hashTable* find(int ikey);
14void insert(int ikey, int ival);
15int* twoSum(int* nums, int numsSize, int target, int* returnSize);
16
17
18//节点群
19static struct hashTable* hashtable;
20
21
22int main(){
23 return 0;
24}
25
26
27//从节点群中找到符合条件的单个节点, 如果找不到, 返回空
28struct hashTable* find(int ikey) {
29 struct hashTable* tmp;
30 HASH_FIND_INT(hashtable, &ikey, tmp);
31 return tmp;
32}
33
34void insert(int ikey, int ival) {
35 //检查是否是重复元素
36 struct hashTable* it = find(ikey);
37 if (it == NULL) {
38 struct hashTable* tmp = malloc(sizeof(struct hashTable));
39 tmp->key = ikey, tmp->val = ival;
40 HASH_ADD_INT(hashtable, ikey, tmp);
41 } else {
42 it->val = ival;
43 }
44}
45
46int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
47 hashtable = NULL;
48 for (int i = 0; i < numsSize; i++) {
49 struct hashTable* it = find(target - nums[i]);
50 if (it != NULL) {
51 int* ret = malloc(sizeof(int) * 2);
52 ret[0] = it->val, ret[1] = i;
53 *returnSize = 2;
54 return ret;
55 }
56 insert(nums[i], i);
57 }
58 *returnSize = 0;
59 return NULL;
60}
61