def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
a = nums[i];
b = target - a ;
for j in range(len(nums)):
if (b == nums[j]) & (i!= j):
return [i,j]
方法二:哈希表 速度:8ms
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
nums_dicts = {};
for i in range(len(nums)):
nums_dicts[nums[i]] = i
for i in range(len(nums)):
a = nums[i]
b = target - a
if b in nums_dicts and nums_dicts[b] != i:
j = nums_dicts[b]
return [i,j]
方法三:chatgpt给出的C语言代码
#include <stdio.h>
#include <stdlib.h>
// 哈希表节点
typedef struct HashNode {
int key;
int value;
struct HashNode* next;
} HashNode;
// 哈希表
typedef struct HashTable {
HashNode** table;
int size;
} HashTable;
// 创建哈希表
HashTable* createHashTable(int size) {
HashTable* hashTable = (HashTable*)malloc(sizeof(HashTable));
hashTable->table = (HashNode**)malloc(sizeof(HashNode*) * size);
for (int i = 0; i < size; i++) {
hashTable->table[i] = NULL;
}
hashTable->size = size;
return hashTable;
}
// 哈希函数
int hashFunction(HashTable* hashTable, int key) {
return abs(key) % hashTable->size;
}
// 插入到哈希表
void insert(HashTable* hashTable, int key, int value) {
int hashIndex = hashFunction(hashTable, key);
HashNode* newNode = (HashNode*)malloc(sizeof(HashNode));
newNode->key = key;
newNode->value = value;
newNode->next = hashTable->table[hashIndex];
hashTable->table[hashIndex] = newNode;
}
// 搜索哈希表
int search(HashTable* hashTable, int key) {
int hashIndex = hashFunction(hashTable, key);
HashNode* node = hashTable->table[hashIndex];
while (node != NULL) {
if (node->key == key) {
return node->value;
}
node = node->next;
}
return -1;
}
// 释放哈希表
void freeHashTable(HashTable* hashTable) {
for (int i = 0; i < hashTable->size; i++) {
HashNode* node = hashTable->table[i];
while (node != NULL) {
HashNode* temp = node;
node = node->next;
free(temp);
}
}
free(hashTable->table);
free(hashTable);
}
// 两数之和函数
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
HashTable* hashTable = createHashTable(numsSize);
for (int i = 0; i < numsSize; i++) {
insert(hashTable, nums[i], i);
}
for (int i = 0; i < numsSize; i++) {
int a = nums[i];
int b = target - a;
int j = search(hashTable, b);
if (j != -1 && j != i) {
int* result = (int*)malloc(sizeof(int) * 2);
result[0] = i;
result[1] = j;
*returnSize = 2;
freeHashTable(hashTable);
return result;
}
}
freeHashTable(hashTable);
*returnSize = 0;
return NULL;
}
// 测试函数
int main() {
int nums[] = {2, 7, 11, 15};
int target = 9;
int returnSize;
int* result = twoSum(nums, 4, target, &returnSize);
if (result != NULL) {
printf("Indices: %d, %d\n", result[0], result[1]);
free(result);
} else {
printf("No solution found.\n");
}
return 0;
}