Coding everyday. ^_^
1. Two Sum
- Key knowledge: the pointer value can be stored by an array of new malloc
- int* returnSize:Size of the return array. Store the value in a pointer, say 2.
*returnSize = 2 - My solution:
-
/** * Note: The returned array must be malloced, assume caller calls free(). */ int* twoSum(int* nums, int numsSize, int target, int* returnSize){ *returnSize = 2; int* returnArray = malloc(sizeof(int)*(*returnSize)); for (int i = 0; i < numsSize-1; i++) { for (int j = i+1; j < numsSize; j++) { if (nums[i] + nums[j] == target) { returnArray[0] = i; returnArray[1] = j; return returnArray; } } } returnArray[0] = -1; returnArray[1] = -1; return returnArray; }
2. Add Two Numbers
- Key knowledge: You can not be calculated by numbers, consider a carry, consider the list traversal and insertion node, the new node by malloc
- Don't use integer to calculate in this problem since the numbers are very long.
- Need to consider carry bit.
- This linked list's head is the first node.
- My solution:
-
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){ struct ListNode* p1; struct ListNode* p2; struct ListNode* l3 = NULL; struct ListNode* p3 = NULL; p1 = l1; p2 = l2; int carry_bit = 0; while (p1 != NULL || p2 != NULL || carry_bit == 1) { int num1; int num2; int num3; if (p1 == NULL && p2 == NULL && carry_bit == 1) { num3 = 1; carry_bit = 0; } else { if (p1 == NULL) { num1 = 0; } else { num1 = p1->val; p1 = p1->next; } if (p2 == NULL) { num2 = 0; } else { num2 = p2->val; p2 = p2->next; } num3 = num1 + num2 + carry_bit; if (num3 >= 10) { carry_bit = 1; num3 = num3 - 10; } else { carry_bit = 0; } } struct ListNode* tmp; tmp = malloc(sizeof(struct ListNode)); if (tmp == NULL) { fprintf(stderr, "Out of memory.\n"); exit(1); } tmp->val = num3; tmp->next = NULL; if (p3 == NULL) { p3 = tmp; l3 = p3; } else { p3->next = tmp; p3 = p3->next; } } return l3; }
3.