给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。 你可以按任意顺序返回答案。 使用C语言实现
时间: 2023-08-14 13:54:41 浏览: 93
```c
#include <stdio.h>
#include <stdlib.h>
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
int* result = (int*)malloc(2 * sizeof(int));
*returnSize = 2;
// 创建哈希表
int hashSize = 10000;
int* hashTable = (int*)malloc(hashSize * sizeof(int));
for (int i = 0; i < numsSize; i++) {
// 计算另一个数的值
int complement = target - nums[i];
// 检查哈希表中是否存在另一个数
if (hashTable[complement % hashSize] != 0) {
result[0] = hashTable[complement % hashSize] - 1;
result[1] = i;
break;
}
// 将当前数加入哈希表
hashTable[nums[i] % hashSize] = i + 1;
}
free(hashTable);
return result;
}
int main() {
int nums[] = {2, 7, 11, 15};
int target = 9;
int returnSize;
int* result = twoSum(nums, sizeof(nums) / sizeof(nums[0]), target, &returnSize);
printf("[%d, %d]\n", result[0], result[1]);
free(result);
return 0;
}
```
这是一个使用哈希表来解决的 C 语言实现。在遍历数组过程中,将每个元素的值和索引存入哈希表中,并在检查到目标元素时返回结果。时间复杂度为 O(n),空间复杂度为 O(n)。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)