语言实例比较 2. 两数之和 C++ Rust Java Python
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例 1:
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.
示例 2:
输入:l1 = [0], l2 = [0]
输出:[0]
示例 3:
输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]
提示:
每个链表中的节点数在范围 [1, 100] 内
0 <= Node.val <= 9
题目数据保证列表表示的数字不含前导零
C++: 32ms, 70.12MB
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *dummyHead = new ListNode();
ListNode *cur = dummyHead;
int sum = 0;
while(l1 || l2 || sum){
if(l1) {
sum += l1->val;
l1 = l1->next;
}
if(l2) {
sum += l2->val;
l2 = l2->next;
}
cur->next = new ListNode(sum % 10, nullptr);
cur = cur->next;
sum = sum / 10;
}
return dummyHead->next;
}
};
Rust: 方法1 递归 4ms, 2.2MB mem
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
impl Solution {
pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
carried(l1, l2, 0)
}
}
pub fn carried(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>, mut carry: i32) -> Option<Box<ListNode>> {
if l1.is_none() && l2.is_none() && carry == 0 {
None
} else {
Some(Box::new(ListNode {
next: carried(
l1.and_then(|x| {carry += x.val; x.next}),
l2.and_then(|x| {carry += x.val; x.next}),
carry / 10
),
val: carry % 10
}))
}
}
Rust: 方法2 迭代 4ms, 2.12MB
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
impl Solution {
pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut l1 = l1;
let mut l2 = l2;
let mut dummy = ListNode::new(0); // 哨兵节点
let mut cur = &mut dummy;
let mut sum = 0; // 剩余和,进位
while l1.is_some() || l2.is_some() || sum != 0 {
l1 = l1.and_then(|node| {sum += node.val; node.next});
l2 = l2.and_then(|node| {sum += node.val; node.next});
cur.next = Some(Box::new(ListNode::new(sum % 10))); // 每个节点保存一个数位
cur = cur.next.as_mut().unwrap(); // 下一个节点
sum = sum / 10; // 新的进位
}
dummy.next // 哨兵节点的下一个节点就是头节点
}
}
Java: 2ms, 43.14MB mem文章来源:https://www.toymoban.com/news/detail-793090.html
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode();
ListNode cur = dummy;
int sum = 0;
while(l1 != null || l2 != null || sum != 0) {
if (l1 != null) { sum += l1.val; l1 = l1.next; }
if (l2 != null) { sum += l2.val; l2 = l2.next; }
cur.next = new ListNode(sum % 10);
cur = cur.next;
sum /= 10;
}
return dummy.next;
}
}
Python: 56ms, 17.5MB mem文章来源地址https://www.toymoban.com/news/detail-793090.html
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
cur = dummy = ListNode()
sum = 0
while l1 or l2 or sum:
if l1: l1, sum = l1.next, sum + l1.val
if l2: l2, sum = l2.next, sum + l2.val
cur.next = ListNode(sum % 10)
cur = cur.next
sum //= 10
return dummy.next
到了这里,关于【笔记】语言实例比较 2. 两数之和 C++ Rust Java Python的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!