当前位置: 首页>移动开发>正文

力扣打卡第一天

101. 对称二叉树

力扣打卡第一天,在这里插入图片描述,第1张

C++:

class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        return check(root->left,root->right);

    }
    bool check(TreeNode *p,TreeNode *q){  /**定义check方法用来检查两棵树是否是镜像的*/
        if (!p && !q) return true;   /* 如果p和q都是空的话,就直接返回true */
        if (!p || !q || p->val != q->val) return false;  /*如果p或q有一个为空或者p和q的值不相等*/
        return check(p->left,q->right) && check(p->right,q->left);  /* 检查p的左子树和q的右子树是否相等,检查p的右子树是否和q的左子树相等 */

    }
};

python:

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return []
        def dfs(left,right):
            if not left and not right:
                return True
            if not left or not right:
                return False
            if left.val != right.val:
                return False
            return dfs(left.left, right.right) and dfs(left.right, right.left)
        return dfs(root.left,root.right)

1.两数之和

力扣打卡第一天,在这里插入图片描述,第2张

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        cache ={}  #用容器cache缓存需要寻找的值
        for idx,num in enumerate(nums):  #enumerate会返回当前的值和下标
            cur = target-num
            if num in cache:
                return [cache[num],idx]
            cache[cur] = idx
        return None

2.两数相加

力扣打卡第一天,在这里插入图片描述,第3张
题目解释:在给出的示例中,2 -> 4 -> 3代表342,5 -> 6 -> 4代表的是465.
2+5=7,4+6=10(有进位,因此第二位为0),得到7 -> 0,然后3+4=7,因为前一位有进位,所以7+1=8,得到7 -> 0 -> 8

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        v = 0   #v代表中间值,加法运算之后可能会超过10和不超过10的中间值
        head = l3 = ListNode(None)   ##设置一个空节点作为指针,方便在过程中进行节点的移动,一开始是空节点None
        while l1 or l2 or v:  ##判断链表l1、l2和中间值是否存在
            v = (l1.val if l1 else 0) + (l2.val if l2 else 0) + v ##判断l1的值是否存在,否则返回0(l2同理),+v代表把v的进位值加到下一轮的v里面
            l3.next = ListNode(v % 10)  #把v的余数赋值给下一个节点
            v = v // 10 #求v的十位是多少,进位数 

            ##加和的逻辑结束,进行指针的移动
            l3 = l3.next
            l1 = l1.next if l1 else None   #(因为l1和l2可能为空)
            l2 = l2.next if l2 else None
        
        return head.next #返回头节点的下一个,因为在头结点的下一个才开始赋值
 

https://www.xamrdz.com/mobile/4td1924270.html

相关文章: