LeetCode c语言刷题总结
文章目录
一、两数之和
题目:
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
源码
#include <stdio.h>
#include <malloc.h>
int* twoSum(int* nums, int numsSize, int target, int* returnSize)
{
for (int i = 0; i < numsSize-1; ++i) {
for (int j = i+1; j < numsSize; ++j) {
int flag = (nums[i] + nums[j]) == target;
if(flag){
int* ret = malloc(sizeof(int) * 2);
ret[0] = i, ret[1] = j;
*returnSize = 2;
return ret;
}
}
}
}
int main()
{
int target = 9;
int nums[] = {2,7,11,15};
int numsSize = 4;
int returnSize = 0;
int *pInt = twoSum(nums, numsSize, target, &returnSize);
printf("%d %d", pInt[0],pInt[1]);
return 0;
}
结果:
总结:
c语言的输入输出真难用,给一个json
格式的list
都难以解析
二、两数相加
题目:
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例 :
源码
#include <stdio.h>
#include <math.h>
#include <malloc.h>
/**
* 节点结构体
*/
typedef struct ListNode{
int val;
struct ListNode *next;
};
/**
* 通过传入的list求其表示的真实数值
* @param head 链表头
* @return 链表代表的值
*/
int valByList(struct ListNode* head){
int retVal = 0;
struct ListNode* p;
p = head;
int count = 0;
while (p->next != NULL){
retVal += pow(10, count) * (p->val);
count++;
p = p->next;
}
retVal += pow(10, count) * (p->val);
return retVal;
}
/**
* 根据数组中的数字构建链表
* @param arr 数组
* @param size 大小
* @return 链表首节点
*/
struct ListNode* buildList(int *arr, int size){
struct ListNode* head;
head = malloc(sizeof(struct ListNode));
struct ListNode* p;
p = head;
for (int i = 0; i < size; ++i) {
p->val = arr[i];
p->next = malloc(sizeof(struct ListNode));
if(i == (size - 1)){
p->next = NULL;
return head;
}
p = p->next;
}
return head;
}
/**
* 将一个已知的值进行反转位题目要求的链表
* @param sum 需要反转的值
* @return 反转后的链表头
*/
struct ListNode* convert(int sum){
int placeCount = 1;
int cache = sum;
while ((cache / 10) != 0){
placeCount++;
cache /= 10;
}
int arr[placeCount];
for (int i = 0; i < placeCount; ++i) {
int placeVal = sum % 10;
sum /=10;
arr[i] = placeVal;
}
struct ListNode *retList = buildList(arr, placeCount);
return retList;
}
/**
* 1.将两个列表转换为数字
* 2.求和
* 3.反转
* @param l1 列表1
* @param l2 列表2
* @return 反转后的数字列表
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
int v1 = valByList(l1);
int v2 = valByList(l2);
int sum = v1 + v2;
return convert(sum);
}
int main()
{
int arr1[] = {2,4,3};
int arr2[] = {5,6,4};
int size1 = 3;
int size2 = 3;
struct ListNode *list1 = buildList(arr1, size1);
struct ListNode *list2 = buildList(arr2, size2);
struct ListNode *retValHead = addTwoNumbers(list1, list2);
int retVal = valByList(retValHead);
printf("%d", retVal);
return 0;
}