runtime 20 ms, beats 99.62% of cpp submissions
O(n) solution with explanation
tags: linked list
๐ link
add two numbers
๐ description
็ตฆๅฎๅ
ฉๅ็ฏ้ป็บๆธๅญ็ linked list ๏ผๅฐๆฏๅ็ฏ้ปไธๅฐไธ็ธๅ ใ
๐ง solution
็ฐกๅฎ็้ปๅฐ้ปๅ ๆณ๏ผไฝ่ฆๆณจๆๅฐๅนพๅไธๅ็ case
- list ็้ทๅบฆไธ็ธๅ
- ้ฒไฝๅ้ก
- ๆ้ซไฝ้ฒไฝ้่ฆๆฐๅข็ฏ้ป
โณ time complexity
้ๆญทๅ
ฉๆข list ไธฆ่จ็ฎๅ ๆณ
็ธฝๆ้่ค้ๅบฆ O(n)
๐ code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { auto head=new ListNode(0); auto head1=head; int carry=0; int sum; while(l1!=nullptr || l2!=nullptr || carry!=0){ sum=0; if(l1!=nullptr){ sum+=l1->val; l1=l1->next; } if(l2!=nullptr){ sum+=l2->val; l2=l2->next; } sum+=carry; if(sum>=10){ carry=1; sum-=10; } else{ carry=0; } auto tmp=new ListNode(sum); head1->next=tmp; head1=head1->next; } return head->next; } };
|