给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]
提示:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
- 哈希表查找,时间复杂度O(n)
- 每遍历一个数,找它的差值是否存在
题解
typedef struct Node {
int val;
int ind;
struct Node *next;
} Node;
typedef struct HashTable {
Node **data;
int size;
} HashTable;
Node *init_Node(int val, Node *head, int ind) {
Node *n = (Node *)malloc(sizeof(Node));
n->val = val;
n->ind = ind;
n->next = head;
return n;
}
HashTable *init(int n) {
HashTable *h = (HashTable *)malloc(sizeof(HashTable));
h->size = n;
h->data = (Node **)calloc(h->size, sizeof(Node));
return h;
}
void insert(HashTable *h, int val, int i) {
if (h == NULL) return ;
int ind = abs(val % h->size);
h->data[ind] = init_Node(val, h->data[ind], i);
return ;
}
Node *search(int val, HashTable *h) {
if (h == NULL) return NULL;
int ind = abs(val % h->size);
Node *p = h->data[ind];
while (p) {
if (p->val == val) return p;
p = p->next;
}
return NULL;
}
void clear_Node(Node *head) {
if (head == NULL) return ;
Node *p = head, *q;
while (p) {
q = p->next;
free(p);
p = q;
}
return ;
}
void clear(HashTable *h) {
if (h == NULL) return ;
for (int i = 0; i < h->size; i++) {
clear_Node(h->data[i]);
}
free(h);
return ;
}
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
HashTable *h = init(numsSize);
for (int i = 0; i < numsSize; i++) {
Node *n = search(target - nums[i], h);
if (n != NULL) {
int *nn = (int *)malloc(sizeof(int) * 2);
nn[1] = i, nn[0] = n->ind;
*returnSize = 2;
clear(h);
return nn;
}
insert(h, nums[i], i);
}
*returnSize = 0;
clear(h);
return NULL;
}
暴力方法
代码演示
/**
* 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++) {
int k = target - nums[i];
for (int j = i + 1; j < numsSize; j++) {
if (k ^ nums[j]) continue;
else {
int *tm = malloc(sizeof(int) * 2);
tm[0] = i, tm[1] = j;
*returnSize = 2;
return tm;
}
}
}
returnSize = 0;
return NULL;
}