ixueaedu 1 anno fa
parent
commit
1f86e203aa
47 ha cambiato i file con 466 aggiunte e 145 eliminazioni
  1. BIN
      .DS_Store
  2. 8 0
      .idea/.gitignore
  3. 19 0
      .idea/inspectionProfiles/Project_Default.xml
  4. 6 0
      .idea/inspectionProfiles/profiles_settings.xml
  5. 8 0
      .idea/leetcode.iml
  6. 4 0
      .idea/misc.xml
  7. 8 0
      .idea/modules.xml
  8. 6 0
      .idea/vcs.xml
  9. 0 0
      .ignore
  10. BIN
      __pycache__/draft.cpython-310-pytest-7.1.2.pyc
  11. BIN
      __pycache__/get_markdown.cpython-38-pytest-7.1.2.pyc
  12. BIN
      __pycache__/is_valid.cpython-38-pytest-7.1.2.pyc
  13. BIN
      __pycache__/merge_two_lists.cpython-310-pytest-7.1.2.pyc
  14. BIN
      __pycache__/merge_two_lists.cpython-38-pytest-7.1.2.pyc
  15. BIN
      __pycache__/merge_two_lists.cpython-39-pytest-7.1.1.pyc
  16. BIN
      __pycache__/merge_two_lists.cpython-39.pyc
  17. BIN
      __pycache__/remove_element.cpython-310-pytest-7.1.2.pyc
  18. BIN
      __pycache__/roman_to_int.cpython-38-pytest-7.1.2.pyc
  19. BIN
      __pycache__/search_insert.cpython-310-pytest-7.1.2.pyc
  20. BIN
      __pycache__/two_sum.cpython-38-pytest-7.1.2.pyc
  21. BIN
      __pycache__/utils.cpython-310.pyc
  22. BIN
      __pycache__/utils.cpython-38-pytest-7.1.2.pyc
  23. BIN
      __pycache__/utils.cpython-38.pyc
  24. BIN
      array/__pycache__/search_insert.cpython-310-pytest-7.1.2.pyc
  25. 7 0
      array/add_binary.py
  26. 14 0
      array/max_profit.py
  27. 16 0
      array/yang_hui_triangle1.py
  28. 15 0
      array/yang_hui_triangle2.py
  29. 36 0
      climb_stairs.py
  30. 0 0
      dichotomy/search_insert.py
  31. 55 0
      double_pointer/has_cycle.py
  32. 33 0
      double_pointer/is_ palindrome.py
  33. 16 0
      double_pointer/is_happy.py
  34. 26 0
      double_pointer/merge_ordered_arrays.py
  35. 0 0
      double_pointer/remove_array_duplicates.py
  36. 7 0
      draft.py
  37. 44 0
      linklist/delete_duplicates.py
  38. 0 0
      linklist/merge_two_lists.py
  39. 2 1
      mySqrt.py
  40. BIN
      string_match/__pycache__/long_common_pre.cpython-310-pytest-7.1.2.pyc
  41. BIN
      tree/__pycache__/tree.cpython-38.pyc
  42. 20 0
      tree/sortedArray_to_bst.py
  43. 5 138
      tree/tree.py
  44. 56 6
      tree/whole_arrang.py
  45. 38 0
      tree/whole_arrang_two.py
  46. 16 0
      utils.py
  47. 1 0
      笔记

BIN
.DS_Store


+ 8 - 0
.idea/.gitignore

@@ -0,0 +1,8 @@
+# Default ignored files
+/shelf/
+/workspace.xml
+# Editor-based HTTP Client requests
+/httpRequests/
+# Datasource local storage ignored files
+/dataSources/
+/dataSources.local.xml

+ 19 - 0
.idea/inspectionProfiles/Project_Default.xml

@@ -0,0 +1,19 @@
+<component name="InspectionProjectProfileManager">
+  <profile version="1.0">
+    <option name="myName" value="Project Default" />
+    <inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
+      <option name="ignoredPackages">
+        <value>
+          <list size="6">
+            <item index="0" class="java.lang.String" itemvalue="tensorboard" />
+            <item index="1" class="java.lang.String" itemvalue="seaborn" />
+            <item index="2" class="java.lang.String" itemvalue="thop" />
+            <item index="3" class="java.lang.String" itemvalue="torch" />
+            <item index="4" class="java.lang.String" itemvalue="torchvision" />
+            <item index="5" class="java.lang.String" itemvalue="pycocotools" />
+          </list>
+        </value>
+      </option>
+    </inspection_tool>
+  </profile>
+</component>

+ 6 - 0
.idea/inspectionProfiles/profiles_settings.xml

@@ -0,0 +1,6 @@
+<component name="InspectionProjectProfileManager">
+  <settings>
+    <option name="USE_PROJECT_PROFILE" value="false" />
+    <version value="1.0" />
+  </settings>
+</component>

+ 8 - 0
.idea/leetcode.iml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module type="PYTHON_MODULE" version="4">
+  <component name="NewModuleRootManager">
+    <content url="file://$MODULE_DIR$" />
+    <orderEntry type="jdk" jdkName="Python 3.8 (py38_schoolcert) (2)" jdkType="Python SDK" />
+    <orderEntry type="sourceFolder" forTests="false" />
+  </component>
+</module>

+ 4 - 0
.idea/misc.xml

@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.8 (py38_schoolcert) (2)" project-jdk-type="Python SDK" />
+</project>

+ 8 - 0
.idea/modules.xml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectModuleManager">
+    <modules>
+      <module fileurl="file://$PROJECT_DIR$/.idea/leetcode.iml" filepath="$PROJECT_DIR$/.idea/leetcode.iml" />
+    </modules>
+  </component>
+</project>

+ 6 - 0
.idea/vcs.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="VcsDirectoryMappings">
+    <mapping directory="$PROJECT_DIR$" vcs="Git" />
+  </component>
+</project>

+ 0 - 0
.gitignore → .ignore


BIN
__pycache__/draft.cpython-310-pytest-7.1.2.pyc


BIN
__pycache__/get_markdown.cpython-38-pytest-7.1.2.pyc


BIN
__pycache__/is_valid.cpython-38-pytest-7.1.2.pyc


BIN
__pycache__/merge_two_lists.cpython-310-pytest-7.1.2.pyc


BIN
__pycache__/merge_two_lists.cpython-38-pytest-7.1.2.pyc


BIN
__pycache__/merge_two_lists.cpython-39-pytest-7.1.1.pyc


BIN
__pycache__/merge_two_lists.cpython-39.pyc


BIN
__pycache__/remove_element.cpython-310-pytest-7.1.2.pyc


BIN
__pycache__/roman_to_int.cpython-38-pytest-7.1.2.pyc


BIN
__pycache__/search_insert.cpython-310-pytest-7.1.2.pyc


BIN
__pycache__/two_sum.cpython-38-pytest-7.1.2.pyc


BIN
__pycache__/utils.cpython-310.pyc


BIN
__pycache__/utils.cpython-38-pytest-7.1.2.pyc


BIN
__pycache__/utils.cpython-38.pyc


BIN
array/__pycache__/search_insert.cpython-310-pytest-7.1.2.pyc


+ 7 - 0
array/add_binary.py

@@ -0,0 +1,7 @@
+def addBinary(a: str, b: str) -> str:
+    a_num = int(a, 2)
+    b_num = int(b, 2)
+    result = a_num + b_num
+    return (bin(result)[2:])
+
+print(addBinary('1010', '1011'))

+ 14 - 0
array/max_profit.py

@@ -0,0 +1,14 @@
+from typing import List
+import heapq
+
+def maxProfit(prices: List[int]) -> int:
+    inf = int(1e9)
+    min_price = inf
+    max_profit = 0
+    for price in prices:
+        max_profit = max(price - min_price, max_profit)
+        min_price = min(price, min_price)
+    return max_profit
+
+
+

+ 16 - 0
array/yang_hui_triangle1.py

@@ -0,0 +1,16 @@
+from typing import List
+
+def generate(numRows: int) -> List[List[int]]:
+    ret = list()
+    for i in range(numRows):
+        res = list()
+        for j in range(0, i + 1):
+            if j == 0 or j == i:
+                res.append(1)
+            else:
+                res.append(ret[i - 1][j - 1] + ret[i - 1][j])
+        ret.append(res)
+
+    return ret
+
+print(generate(5))

+ 15 - 0
array/yang_hui_triangle2.py

@@ -0,0 +1,15 @@
+from typing import List
+
+def getRow(rowIndex: int) -> List[int]:
+    ret = list()
+    for i in range(rowIndex + 1):
+        res = list()
+        for j in range(0, i + 1):
+            if j == 0 or j == i:
+                res.append(1)
+            else:
+                res.append(ret[i - 1][j - 1] + ret[i - 1][j])
+        ret.append(res)
+    return res
+
+print(getRow(6))

+ 36 - 0
climb_stairs.py

@@ -0,0 +1,36 @@
+# def climbStairs(n: int) -> int:
+#     if n < 1 or n > 45:
+#         return 0
+#     else:
+#         a = 1
+#         b = 1
+#         for i in range(2, n + 1):
+#             a, b = b, a + b
+#         return b
+
+# print(climbStairs(4))
+
+def f(n):
+    cach = {}
+    def g(n):
+        if n == 1:
+            return 1
+        if n == 2:
+            return 2
+        else:
+            if n-1 in cach:
+                f1 = cach[n-1]
+            else:
+                f1 = g(n-1)
+                cach[n-1] = f1
+            if n-2 in cach:
+                f2 = cach[n-2]
+            else:
+                f2 = g(n-2)
+                cach[n-2] = f2
+        return f1 + f2
+    return g(n)
+
+print(f(4))
+
+

+ 0 - 0
array/search_insert.py → dichotomy/search_insert.py


+ 55 - 0
double_pointer/has_cycle.py

@@ -0,0 +1,55 @@
+from typing import Optional
+
+import pytest
+
+from utils import ListNode, arr_to_linklist
+
+def hasCycle(head: Optional[ListNode]) -> bool:
+    # if not head or not head.next:
+    #     return False
+    # p = q = head
+    # while p.next or q.next:
+    #     if q.next is None:
+    #         p = p.next
+    #         q = p.next
+    #     elif p.next is None:
+    #         return False
+    #     elif q.next != p:
+    #         q = q.next
+    #     else:
+    #         return True
+
+    # 哈希表法
+    # res = set()
+    # while head:
+    #     if head in res:
+    #         return True
+    #     res.add(head)
+    #     head = head.next
+    # return False
+
+    # 快慢指针法
+    if not head or not head.next:
+        return False
+    slow = head
+    fast = head.next
+    while fast != slow:
+        if not fast or not fast.next:
+            return False
+        slow = slow.next
+        fast = fast.next.next
+
+    return True
+
+
+
+
+@pytest.mark.parametrize(
+    "head, expect",
+    [
+        ([3,2,0,-4], True)
+    ]
+)
+
+def test_cases(head, expect):
+    assert hasCycle(arr_to_linklist(head)) == expect

+ 33 - 0
double_pointer/is_ palindrome.py

@@ -0,0 +1,33 @@
+import pytest
+
+
+def isPalindrome(s: str):
+    s = ''.join(ch for ch in s if ch.isalnum()).lower()
+    if s == '':
+        return True
+    lens = len(s)
+    p, q = 0, lens - 1
+    while p < lens or q > 0:
+        if p >= q:
+            return True
+        elif s[p] == s[q]:
+            p += 1
+            q -= 1
+        else:
+            return False
+
+@pytest.mark.parametrize(
+    "s, expect",
+    [
+        ("", True),
+        (".", True),
+        ("aa", True),
+        ("A man, a plan, a canal: Panama", True),
+        ("a123a", False)
+    ]
+)
+
+def test_cases(s, expect):
+    assert isPalindrome(s) == expect
+
+

+ 16 - 0
double_pointer/is_happy.py

@@ -0,0 +1,16 @@
+import math
+def isHappy(n: int) -> bool:
+    if n == 1:
+        return True
+    while n != 1:
+        n = str(n)
+        a = 0
+        for i in n:
+            i = int(i)
+            a = i * i + a
+        if a < 10 and a > 1 and a != 7:
+            return False
+        n = a
+    return True
+
+print(isHappy(2))

+ 26 - 0
double_pointer/merge_ordered_arrays.py

@@ -0,0 +1,26 @@
+from typing import List
+
+def merge(nums1: List[int], m: int, nums2: List[int], n: int) -> None:
+    # 法1
+    nums1[m:] = nums2
+    nums1.sort()
+
+    #双指针
+    Sort = []
+    p1, p2 = 0, 0
+    while p1 < m or p2 < n:
+        if p1 == m:
+            Sort.append(nums2[p2])
+            p2 += 1
+        elif p2 == n:
+            Sort.append(nums1[p1])
+            p1 += 1
+        elif nums1[p1] <= nums2[p2]:
+            Sort.append(nums1[p1])
+            p1 += 1
+        else:
+            Sort.append(nums2[p2])
+            p2 += 1
+    nums1[:] = Sort
+
+print(merge(nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3))

+ 0 - 0
array/remove_array_duplicates.py → double_pointer/remove_array_duplicates.py


+ 7 - 0
draft.py

@@ -1,4 +1,11 @@
+<<<<<<< HEAD
 import numpy as np
 n = 3
 m = np.array(range(1, (n * n) + 1)).reshape(n, n)
 print(m)
+=======
+s = "A man, a plan, a canal: Panama".lower()
+b = ''.join(ch for ch in s if ch.isalnum()).lower()
+print(b)
+
+>>>>>>> 0ac0c7a7a7ace7b2c81857019fe6ed8ad32cad09

+ 44 - 0
linklist/delete_duplicates.py

@@ -0,0 +1,44 @@
+from typing import Optional
+from utils import ListNode, list_to_linklist, deleteNode, linkList_to_arr
+
+def deleteDuplicates(head: Optional[ListNode]) -> Optional[ListNode]:
+    if not head:
+        return head
+    # p = head
+    # while p.next:
+    #     if p.val == p.next.val:
+    #         p.next = p.next.next
+    #     else:
+    #         p = p.next
+    #
+    # return head
+    # p = head
+    # while p and p.next:
+    #     q: ListNode = p.next
+    #     # 寻找跟p不同val的节点
+    #     # 找到的时候q指向了它
+    #     while q and q.val == p.val:
+    #         q = q.next
+    #     p.next = q
+    #     p = q
+    # return head
+
+    p = head
+    q = head.next
+    while q:
+        if q.val == p.val:
+            p.next = q.next
+            q = q.next
+        else:
+            p = q
+            q = q.next
+
+    return head
+
+res = deleteDuplicates(list_to_linklist([1]))
+print(linkList_to_arr(res))
+
+
+
+
+

+ 0 - 0
array/merge_two_lists.py → linklist/merge_two_lists.py


+ 2 - 1
mySqrt.py

@@ -14,11 +14,12 @@ def mySqrt(x: int) -> int:
 
     l, r, ans = 0, x, -1
     while l <= r:
-        mid = (l + r) // 2
+        mid = l + (r - l) // 2
         if mid * mid <= x:
             ans = mid
             l = mid + 1
         else:
             r = mid - 1
     return ans
+
 print(mySqrt(10))

BIN
string_match/__pycache__/long_common_pre.cpython-310-pytest-7.1.2.pyc


BIN
tree/__pycache__/tree.cpython-38.pyc


+ 20 - 0
tree/sortedArray_to_bst.py

@@ -0,0 +1,20 @@
+from typing import List, Optional
+from tree import TreeNode
+
+
+class Solution:
+    def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
+        if not nums:
+            return
+        mid = len(nums) // 2
+        root = TreeNode(nums[mid])
+
+        if mid == 0:
+            return root
+
+        root.left = self.sortedArrayToBST(nums[:mid])
+        root.right = self.sortedArrayToBST(nums[mid + 1:])
+
+        return root
+
+

+ 5 - 138
tree/tree.py

@@ -1,142 +1,9 @@
-#列表函数
-def BinaryTree(r):
-    return [r, [], []]
 
-#插入左子树
-def insertLeft(root, newBranch):
-    t = root.pop(1)
-    if len(t) > 1:
-        root.insert(1, [newBranch, t, []])
-    else:
-        root.insert(1, [newBranch, [], []])
-    return root
-
-#插入右子树
-def insertRight(root, newBranch):
-    t = root.pop(2)
-    if len(t) > 1:
-        root.insert(2, [newBranch, [], t])
-    else:
-        root.insert(2, [newBranch, [], []])
-    return root
-
-#树的访问函数
-def getRootVal(root):
-    return root[0]
-
-def setRootVal(root, newval):
-    root[0] = newval
-
-def getLeftChild(root):
-    return root[1]
-
-def getRightChild(root):
-    return root[2]
-
-
-# 二叉树的访问函数
-def getLeftChild(self):
-    return self.leftChild
-
-def getRightChild(self):
-    return self.rightChild
-
-def setRootValue(self, obj):
-    self.key = obj
-
-def getRootValue(self):
-    return self.key
-
-
-# 定义节点
-class BinaryTree:
-    def __init__(self, rootObj):
-        self.key = rootObj
-        self.leftChild = None    # 左子节点也是树
-        self.rightChild = None    # 右子节点也是树
-
-# 插入左子节点
-def insertLeft(self, newNode):
-    if self.leftChild == None:
-        self.leftChild = newNode
-    else:
-        t = BinaryTree(newNode)
-        t.leftChild = self.leftChild
-        self.leftChild = t
-
-# 插入右子节点
-def insertRight(self, newNode):
-    if self.rightChild == None:
-        self.rightChild = newNode
-    else:
-        t = BinaryTree(newNode)
-        t.rightChild = self.rightChild
-        self.rightChild = t
-
-# 树的遍历
-
-# 前序
-def preorder(tree):
-    if tree:
-        print(tree.getRootVal())
-        preorder(tree.getLeftChild())
-        preorder(tree.getRightChild())
-
-# 中序
-def inorder(tree):
-    if tree:
-        inorder(tree.getLeftChild())
-        print(tree.getRootVal())
-        inorder(tree.getRightChild())
-
-# 后序
-def postorder(tree):
-    if tree:
-        postorder(tree.getLeftChild())
-        postorder(tree.getRightChild())
-        print(tree.getRootVal())
-
-# 树
-# class Bnode(object):
-#     def __init__(self, data, left=None, right=None):
-#         self.data = data
-#         self.left = left
-#         self.right = right
-#
-# class Btree(object):
-#     def __init__(self, root=None):
-#         self.root = root
-#
-#     @classmethod
-#     def bulid(cls, list):
-#         node_dict = {}
-#         # 制作节点
-#         for item in list:
-#             data = item['data']
-#             node_dict[data] = Bnode(data)
-#         # 把节点组装成数
-#         for item in list:
-#             data = item['data']
-#             node = node_dict[data]
-#             if node['is_root']:
-#                 root = node
-#             node.left = node_dict.get(item['left'])
-#             node.right = node_dict.get(item['right'])
-#         return cls(root)
-#
-#     def preorder(self, subtree):
-#         # 先序
-#         if subtree is not None:
-#             print(subtree.data)
-#             self.preorder(subtree.left)
-#             self.preorder(subtree.right)
-#
-#     def reverse(self, subtree):
-#         # 后序
-#         if subtree is not None:
-#             subtree.left, subtree.right = subtree.right, subtree.left
-#             self.reverse(self, subtree.left)
-#             self.reverse(self, subtree.right)
+class TreeNode:
+    def __init__(self, val=0, left=None, right=None):
+        self.val = val
+        self.left = left
+        self.right = right
 
 # 回溯通用模板
 # res = []

+ 56 - 6
tree/whole_arrang.py

@@ -1,7 +1,57 @@
-def addBinary(a: str, b: str) -> str:
-    a_num = int(a, 2)
-    b_num = int(b, 2)
-    result = a_num + b_num
-    return (bin(result)[2:])
+from typing import List
+class Solution:
+    def permute(self, nums: List[int]) -> List[List[int]]:
 
-print(addBinary('1010', '1011'))
+
+        def dfs(nums, size, depth, path, used, res):
+            if depth == size:
+                res.append(path[:])
+
+                return
+
+            for i in range(size):
+                # used[i] 为 false时
+                if not used[i]:
+                    used[i] = True
+                    path.append(nums[i])
+
+                    def dfs(nums, size, depth, path, used, res):
+                        if depth == size:
+                            res.append(path[:])
+
+                            return
+
+                        for i in range(size):
+                            # used[i] 为 false时
+                            if not used[i]:
+                                used[i] = True
+                                path.append(nums[i])
+
+                                dfs(nums, size, depth + 1, path, used, res)
+
+                                used[i] = False
+                                path.pop()
+
+                    used[i] = False
+                    path.pop()
+
+        size = len(nums)
+        if len(nums) == 0:
+            return []
+
+        # 一维数组赋值
+        used = [False for _ in range(size)]
+        # 二维数组赋值
+        # [[False for _ in range(size)] for _ in range(size)]
+        res = []
+        dfs(nums, size, 0, [], used, res)
+
+
+        return res
+
+
+if __name__ == '__main__':
+    nums = [1, 2, 3]
+    solution = Solution()
+    res = solution.permute(nums)
+    print(res)

+ 38 - 0
tree/whole_arrang_two.py

@@ -0,0 +1,38 @@
+from typing import List
+
+
+class Solution:
+    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
+        def dfs(nums, size, depth, path, res, used):
+            if depth == size:
+                if path not in res:
+                    res.append(path[:])
+                return
+
+            for i in range(size):
+                if not used[i]:
+                    used[i] = True
+                    path.append(nums[i])
+
+                    dfs(nums, size, depth + 1, path, res, used)
+
+                    used[i] = False
+                    path.pop()
+
+        size = len(nums)
+        if len(nums) == 0:
+            return []
+
+        used = [False for _ in range(size)]
+        res = []
+
+        dfs(nums, size, 0, [], res, used)
+
+        return res
+
+if __name__ == "__main__":
+    nums = [1, 1, 3]
+    solution = Solution()
+    res = solution.permuteUnique(nums)
+    print(res)
+

+ 16 - 0
utils.py

@@ -35,4 +35,20 @@ def list_to_linklist(arr):
         p = p.next
     return head
 
+# 计算链表长度
+def len_of_linklist(head):
+    lens = 0
+    p = head
+    while p:
+        lens += 1
+        p = p.next
+    return lens
+
+def deleteNode(node):
+    node.val = node.next.val
+    node.next = node.next.next
+
+
+
+
 

+ 1 - 0
笔记

@@ -0,0 +1 @@
+有排序:用双指针