zoukankan      html  css  js  c++  java
  • 算法练习题

    1.TwoSum

      给一个int型数组,要求找出其中两个和为特定值得数的坐标

      注意点:

        返回的左表一要比坐标二小

        最小的坐标是1,不是0

      例子:

      输入:numbers={2,7,11,15},target=9 输出:index1=1,index2=2

    解:

    def twoSum(nums,target):
        hash_map = {}
        for index,value in enumerate(nums):
            hash_map[value] = index
        print(hash_map)
        for index1,value in enumerate(nums):
            if target - value in hash_map:
                index2 = hash_map[target-value]
                if index1 != index2:
                    return [index1+1,index2+1]
    View Code

    2.Add Two Numbers

      定义这样的一个链表,链表的每个节点都存有一个0-9的数字,把链表当成数字,表头为高位,表尾为低位。如1->2->3表示321,现在要对两个这样的链表求和。

      注意点:

        数字的高低位,应该从低位向高位进位

        有多种情况要考虑,如链表长度是否相等、是否进位等

      例子:

      输入:(2->4->3)+(5->6->4) 输出:7->0->8

    解:

    class ListNode:
        def __init__(self,x):
            self.val = x
            self.next = None
            
        def myPrint(self):
            print(self.val)
            if self.next:
                self.next.myPrint()
    
    
    def addTwoNodes(n1,n2):
        if not n1 and not n2:
            pass
        if not n1:
            return n2.val
        if not n2:
            return n1.val
        return n1.val+n2.val
    
    def addTwoNumbers(l1,l2):
        result = ListNode(0)
        cur = result
        while l1 or l2:
            cur.val += addTwoNodes(l1,l2)
            if cur.val >=10:
                cur.val -= 10
                cur.next = ListNode(1)
            else:
                if l1 and l1.next or l2 and l2.next:
                    cur.next = ListNode(0)
            cur = cur.next
            if l1:
                l1 = l1.next
            if l2:
                l2 = l2.next
        return result
    
    lst = ListNode(9)
    lst.next = ListNode(8)
    addTwoNumbers(lst,ListNode(1)).myPrint()
    View Code
  • 相关阅读:
    2021.2.6 日记
    P2168 荷马史诗
    2021寒假集训——数论初步
    2021.2.5 日记
    2021.2.4 日记
    2021.2.3 日记
    堆——学习笔记
    树状数组——学习笔记
    Easy | LeetCode 350. 两个数组的交集 II | 哈希 | 排序+双指针
    Easy | LeetCode 66. 加一 | 模拟
  • 原文地址:https://www.cnblogs.com/muchengQ/p/11939362.html
Copyright © 2011-2022 走看看