Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 308683c

Browse files
Refine
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent 3649f22 commit 308683c

File tree

3 files changed

+44
-30
lines changed

3 files changed

+44
-30
lines changed

001_two_sum/two_sum.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,10 @@ int main(void)
4747
//int nums[] = {0,4,3,0};
4848
//int target = 0;
4949
int nums[] = { 3, 2, 3 };
50-
int count = sizeof(nums) / sizeof(*nums);
50+
int size = sizeof(nums) / sizeof(*nums);
5151
int target = 6;
52-
int *indexes = twosum(nums, count, target);
52+
int count = 0;
53+
int *indexes = twosum(nums, size, target, &count);
5354
if (indexes != NULL) {
5455
printf("%d %d\n", indexes[0], indexes[1]);
5556
} else {

001_two_sum/two_sum.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class Solution:
2+
def twoSum(self, nums, target):
3+
h = {}
4+
for i, n in enumerate(nums):
5+
other = target - n
6+
if other not in h:
7+
h[n] = i
8+
else:
9+
return [h[other], i]
10+
11+
print(Solution().twoSum([-1, -2, -3, -4, -5], -8))

002_add_two_numbers/add_two_numbers.c

Lines changed: 30 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -10,48 +10,50 @@ struct ListNode {
1010

1111
static struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2)
1212
{
13-
int carry_num = 0;
14-
int first = 1;
15-
struct ListNode *res = NULL;
16-
struct ListNode *p = NULL;
17-
struct ListNode *prev = p;
13+
int carry = 0;
14+
struct ListNode dummy;
15+
struct ListNode *p = l1, *prev = &dummy;
1816

19-
while (l1 != NULL || l2 != NULL || carry_num) {
17+
dummy.next = p;
18+
while (l1 != NULL || l2 != NULL) {
2019
int sum = 0;
21-
int last_carry = carry_num;
20+
int last_carry = carry;
21+
2222
if (l1 != NULL) {
23+
if (p == NULL) {
24+
/* p never be NULL */
25+
prev->next = l1;
26+
p = l1;
27+
}
2328
sum += l1->val;
2429
l1 = l1->next;
2530
}
31+
2632
if (l2 != NULL) {
33+
if (p == NULL) {
34+
/* p never be NULL */
35+
prev->next = l2;
36+
p = l2;
37+
}
2738
sum += l2->val;
2839
l2 = l2->next;
2940
}
30-
if (sum >= 10) {
31-
sum -= 10;
32-
carry_num = 1;
33-
} else {
34-
carry_num = 0;
35-
}
41+
42+
sum += last_carry;
43+
carry = sum / 10;
44+
p->val = sum % 10;
45+
prev = p;
46+
p = p->next;
47+
}
3648

49+
if (carry) {
3750
p = malloc(sizeof(*p));
38-
if (first) {
39-
res = p;
40-
first = 0;
41-
}
42-
p->val = sum + last_carry;
43-
if (p->val >= 10) {
44-
p->val -= 10;
45-
carry_num = 1;
46-
}
51+
p->val = carry;
4752
p->next = NULL;
48-
if (prev != NULL) {
49-
prev->next = p;
50-
}
51-
prev = p;
53+
prev->next = p;
5254
}
53-
54-
return res;
55+
56+
return dummy.next;
5557
}
5658

5759
static struct ListNode *node_build(const char *digits)

0 commit comments

Comments
 (0)