宝宝刷 leetcode

12/3

1、Two Sum

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dict = {}
        for i in range(len(nums)):
            j = target - nums[i]
            if j in dict:
                return [dict[j],i]
            else:
                dict[nums[i]] = i 
        #return 0

2. Add Two Numbers

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        ans = 0
        unit = 1
        while l1 or l2:
            if l1:
                ans += l1.val * unit
                l1 = l1.next
            if l2:
                ans += l2.val * unit
                l2 = l2.next
            unit *= 10

        alpha = cur = ListNode(0)

        for n in reversed(str(ans)):
            cur.next = ListNode(int(n))
            cur = cur.next
    
        return alpha.next

补充:链表是由一些节点构成的,这些节点之间由指针连接,形成了一个链式结构。最基本的链表节点只需要存储当前节点的值,和一个指向下一节点的指针。由这种只存储下一节点地址的链表节点构成的链表被称为单向链表。

在节点ListNode定义中,定义为节点为结构变量。节点存储了两个变量:value 和 next。value 是这个节点的值,next 是指向下一节点的指针,当 next 为空指针时,这个节点是链表的最后一个节点。构造函数包含两个参数 _value 和 _next ,分别用来给节点赋值和指定下一节点。

struct ListNode {
       int val;    //定义val变量值,存储节点值
       struct ListNode *next;   //定义next指针,指向下一个节点,维持节点连接
  }

203. Remove Linked List Elements( 类比 83. Remove Duplicates from Sorted List)

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
class Solution:
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        if head == None:
            return head
        dummy = ListNode(0)
        dummy.next = head
        pre = dummy
        while head:
            if head.val == val:
                pre.next = head.next
                head = pre
            pre = head
            head = head.next
        return dummy.next

(链表)206. Reverse Linked List

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
class Solution:
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        tail = None
        cur = head
        while cur:
            next_node = cur.next  #存储当前节点的指向
            cur.next = tail       #当前节点指向尾节点,(改变指针指向)
            tail = cur
            cur = next_node
        return tail

21. Merge Two Sorted Lists

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
class Solution:
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        head = ListNode(0)
        cur = head

        while l1 and l2:

            if l1.val > l2.val:
                cur.next = l2
                l2 = l2.next

            else:
                cur.next = l1
                l1 = l1.next

            cur = cur.next

        cur.next = l1 or l2

        return head.next

26. Remove Duplicates from Sorted Array

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.
class Solution:
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        cnt=0
        if (len(nums)==0):
            return cnt 

        for i in sorted(set(nums)):
     #set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。 nums[cnt]
=i cnt+=1 return cnt

27. Remove Element

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
class Solution:
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        index = 0
        while(index < len(nums)):
            if (nums[index] == val):
                nums.pop(nums.index(val))
#pop()指定删除对象的索引位置,例如,a.pop(3)要删除列表a中索引3对应的元素。
else: index += 1

88. Merge Sorted Array

Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

Output: [1,2,2,3,5,6]
class Solution:
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: void Do not return anything, modify nums1 in-place instead.
        """
        for v in nums2:
            nums1[m] = v
            m+=1
        nums1.sort()

 (二叉树)111. Minimum Depth of Binary Tree

Given binary tree [3,9,20,null,null,15,7],

    3
   / 
  9  20
    /  
   15   7

return its minimum depth = 2.

class Solution:
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root: 
            return 0 
        
        children = [root.left, root.right]
        # if we're at leaf node
        if not any(children):
            return 1
        
        min_depth = float('inf')
        for c in children:
            if c:
                min_depth = min(self.minDepth(c), min_depth)
        return min_depth + 1

12/4

563. Binary Tree Tilt

Example:

Input: 
         1
       /   
      2     3
Output: 1
Explanation: 
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1
class Solution:
    def findTilt(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.res = []
        if not root:
            return 0
        self.dfs(root)
        return sum(self.res)
    def dfs(self,root):
        if not root:
            return 0
        if not root.left and not root.right:
            return root.val
        leftsum = self.dfs(root.left)
        rightsum = self.dfs(root.right)
        self.res.append(abs(leftsum - rightsum))
        return root.val + leftsum + rightsum

102. 二叉树的层次遍历

    3
   / 
  9  20
    /  
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]
class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        # write code here
        if not root:
            return []
        queue=[root]
        outList=[]
        while queue:
            res=[]
            nextQueue=[]
            for point in queue:     #这里再遍历每一层
                res.append(point.val)
                if point.left:
                    nextQueue.append(point.left)
                if point.right:
                    nextQueue.append(point.right)
            outList.append(res)
            queue=nextQueue     #这一步很巧妙,用当前层覆盖上一层
        return outList

83. Remove Duplicates from Sorted List

Input: 1->1->2->3->3
Output: 1->2->3
class Solution:
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head is None:
            return head
        cur = head
        while cur.next:
            if cur.val == cur.next.val:
                cur.next = cur.next.next
                continue
            cur = cur.next
        return head

237. Delete Node in a Linked List

 4 -> 5 -> 1 -> 9
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        node.val = node.next.val
        node.next = node.next.next

35. Search Insert Position

Input: [1,3,5,6], 5
Output: 2
Input: [1,3,5,6], 2
Output: 1
class Solution:
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        index = 0
        for i in nums:
            diff = target - i            
            if diff > 0:
                index += 1
            else:
                break                
        return index

724. Find Pivot Index

Input: 
nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation: 
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
Also, 3 is the first index where this occurs.
class Solution:
    def pivotIndex(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        lefty, righty = 0, sum(nums[1:])
        if nums and lefty == righty:
            return 0
        for i in range(1, len(nums)):
            lefty += nums[i-1]
            righty -= nums[i]
            if lefty == righty:
                return i
        return -1 

674. Longest Continuous Increasing Subsequence

Input: [1,3,5,4,7]
Output: 3
class Solution:
    def findLengthOfLCIS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        dp = [1] * len(nums)
        for i in range(1, len(nums)):
            if nums[i] > nums[i-1]:
                dp[i] = dp[i - 1] + 1
        return max(dp)
#返回最长序列的起始索引
#return dp.index(max(dp))-max(dp)+1

108. Convert Sorted Array to Binary Search Tree

class Solution:
    def sortedArrayToBST(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        if not nums:
            return None

        mid = len(nums) // 2
        #" // "来表示整数除法,返回不大于结果的一个最大的整数,而" / " 则单纯的表示浮点数除法

        root = TreeNode(nums[mid])
        root.left = self.sortedArrayToBST(nums[:mid])
        root.right = self.sortedArrayToBST(nums[mid+1:])

        return root

 169. Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

Input: [3,2,3]
Output: 3
class Solution:
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        a = int(len(nums)/2)
        b = collections.Counter(nums)
        for i in nums:
            if b[i]>a:
                return i

242. Valid Anagram

Input: s = "anagram", t = "nagaram"
Output: true
class Solution:
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        return collections.Counter(s) == collections.Counter(t)
#Counter(计数器)是对字典的补充,用于追踪值的出现次数。

283. Move Zeroes

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
class Solution:
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """   
        length = len(nums)
        i = 0
        while i < length:
            
            if nums[i] == 0:
                nums.append(nums.pop(i))
                length -= 1
                continue

            i += 1

268. Missing Number

Input: [9,6,4,2,3,5,7,0,1]
Output: 8
class Solution:
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        length=len(nums)
        return (int((length**2+length)/2))-sum(nums)

387. First Unique Character in a String

s = "loveleetcode",
return 2.
class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        hash_table = {e:index for index, e in enumerate(s)}
        
        for index,e in enumerate(s):
            if e in hash_table:
                if hash_table[e]==index:
                    return index
                del hash_table[e]
        return -1

13. Roman to Integer

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000
Input: "III"
Output: 3
Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
class Solution:
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        dic = {'M':1000,
                 'D':500,
                 'C':100,
                 'L':50,
                 'X':10,
                 'V':5,
                 'I':1}
        
        temp = 0
        res = 0
        for c in s:
            if dic[c] > temp:
                res -= 2 * temp
            temp = dic[c]    
            res += temp
        
        return res

350. Intersection of Two Arrays II

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
class Solution:
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        counts = collections.Counter(nums1)
        res = []

        for num in nums2:
            if counts[num] > 0:
                res.append(num)
                counts[num] -= 1

        return res

 2019/3/29

28. 实现strStr()

(如何判断一个字符串是否包含另一个字符串)

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        m = len(haystack)
        n = len(needle)
        for i in range(m-n+1):
            if haystack[i:i+n] == needle:
                return i
        return -1

26. 删除排序数组中的重复项

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)
        
        j = 0
        for i in range(n-1):
            if nums[i] == nums[i+1]:
                nums[j] = nums[i]
                
            else:
                nums[j] = nums[i]
                nums[j+1] = nums[i+1]
                j = j+1
                
        return j+1

35. 搜索插入位置

class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        n = len(nums)
        
        if target > nums[n-1]:
            return n
        elif target < nums[0]:
            return 0
        for i in range(n):
            while target == nums[i]:
                return i
            while target > nums[i] and target < nums[i+1]:
                return i+1

 7. 整数反转

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        string = str(x)
        if x < 0:
            string = "-" + string[len(string):0:-1].lstrip("0")
        elif x > 0:
            string = string[::-1].lstrip("0")
        else:
            string = "0"
        if -2**31<int(string)<2**31-1:
            return int(string)
        else:
            return 0
            


原文地址:https://www.cnblogs.com/feifanrensheng/p/10060583.html