记录leetcode刷题过程
001 Two Sum
Given an array of integers, return indices of the two numbers such that
they add up to a specific target. You may assume that each input would
have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
C语言太久没碰,语法都忘了
1.忘了malloc的用法int *array = (int*)malloc(2*sizeof(int));
2.混用=
和==
3.代码最终返回位置没放好 4.字母numsSize
看漏了一个s
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
int *array = (int*)malloc(2*sizeof(int));
for(int i = 0; i < numsSize - 1; i++)
for(int j = i + 1; j < numsSize; j++)
if(nums[i] + nums[j] == target){
array[0] = i;
array[1] = j;
}
return array;
}
002 Add Two Numbers
You are given two non-empty linked lists representing two non-negative
integers. The digits are stored in reverse order and each of their nodes
contain a single digit. Add the two numbers and return it as a linked
list. You may assume the two numbers do not contain any leading zero,
except the number 0 itself. Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
1.涉及知识点,链表的头插法和尾插法,站和队列的应用
2.遇到的问题,指针传值和引用分不清,分配指针悬空
3.提高,遇到问题前可以自模拟几种极端情况
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int len1 = 1, len2 = 1;
int temp = 0;
int i, j;
struct ListNode* p = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* t = p;
//将链表存在队列里
struct ListNode* t1 = l1;
struct ListNode* t2 = l2;
for(; t1->next != NULL; len1++, t1 = t1->next);
for(; t2->next != NULL; len2++, t2 = t2->next);
int *p1 = (int *)malloc(len1*sizeof(int));
int *p2 = (int *)malloc(len2*sizeof(int));
for(int i = 0; l1 != NULL; i++){
*(p1+i) = l1->val;
l1 = l1->next;
}
for(int i = 0; l2 != NULL; i++){
*(p2+i) = l2->val;
l2 = l2->next;
}
//叠加链表公共长度部分
for(i = 0, j = 0; i < len1 && j < len2; i++, j++){ struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode)); node->val = (*(p1 + i) + *(p2 + j) + temp) % 10;
node->next = NULL;
t->next = node;
t = t->next;
temp = (*(p1 + i) + *(p2 + j) + temp) / 10;
}
//链表多余长度部分
if(len1 > len2) {
for(;i < len1; i++){ struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode)); node->val = (*(p1 + i) + temp) % 10;
node->next = NULL;
t->next = node;
t = t->next;
temp = (*(p1 + i) + temp) / 10;
}
}
if(len2 > len1) {
for(;j < len2; j++){ struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode)); node->val = (*(p2 + j) + temp) % 10;
node->next = NULL;
t->next = node;
t = t->next;
temp = (*(p2 + j) + temp) / 10;
}
}
//最后的进位
if(temp == 1){
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = 1;
node->next = NULL;
t->next = node;
}
return p->next;
}