解锁LeetCode C语言难题,一题一解,助你高效通关!

引言
LeetCode作为全球最受欢迎的在线编程平台之一,提供了各种难度级别的编程题目,其中C语言题目尤为受到编程爱好者和求职者的青睐。本文将针对LeetCode上的C语言难题,一题一解,帮助读者高效通关。
第一题:两数之和
题目描述
给定一个整数数组
nums
和一个目标值
target
,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
解题思路
使用哈希表存储数组中每个数字的值和对应的索引,遍历数组时,对于每个元素,检查
target – nums[i]
是否存在于哈希表中,如果存在,则返回当前索引和哈希表中对应值的索引。
代码实现
#include
#include

int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
int* result = (int*)malloc(2 * sizeof(int));
*returnSize = 2;
int hash[1001] = {0}; // 假设数组元素在-1000到1000之间

for (int i = 0; i < numsSize; i++) { if (hash[target - nums[i]] != 0) { result[0] = hash[target - nums[i]]; result[1] = i; return result; } hash[nums[i]] = i; } return NULL; } int main() { int nums[] = {2, 7, 11, 15}; int target = 9; int returnSize; int* result = twoSum(nums, sizeof(nums) / sizeof(nums[0]), target, &returnSize); if (result != NULL) { printf("Index1: %d, Index2: %d\n", result[0], result[1]); } else { printf("No solution found.\n"); } free(result); return 0; } 时间复杂度和空间复杂度分析 时间复杂度:O(n),其中n为数组长度。 空间复杂度:O(n),其中n为数组长度。 第二题:合并两个有序链表 题目描述 将两个升序链表合并为一个新的升序链表并返回。 解题思路 使用递归方法,比较两个链表的头节点,将较小的节点连接到新的链表,然后递归地处理剩余的链表。 代码实现 #include
#include

struct ListNode {
int val;
struct ListNode *next;
};

struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;

if (l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}

int main() {
// 示例代码,创建两个链表并合并
// …
return 0;
}
时间复杂度和空间复杂度分析
时间复杂度:O(m+n),其中m和n分别为两个链表的长度。
空间复杂度:O(m+n),其中m和n分别为两个链表的长度。
总结
通过以上两道题目的解析和代码实现,读者可以了解到LeetCode C语言难题的解题思路和技巧。希望本文能够帮助读者在LeetCode上取得更好的成绩。