sxkj 2 years ago
commit
2ccbfde270
3 changed files with 60 additions and 0 deletions
  1. 2 0
      .gitignore
  2. 16 0
      main.py
  3. 42 0
      two_sum.py

+ 2 - 0
.gitignore

@@ -0,0 +1,2 @@
+/.idea/
+__pycache__/

+ 16 - 0
main.py

@@ -0,0 +1,16 @@
+# This is a sample Python script.
+
+# Press ⌃R to execute it or replace it with your code.
+# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
+
+
+def print_hi(name):
+    # Use a breakpoint in the code line below to debug your script.
+    print(f'Hi, {name}')  # Press ⌘F8 to toggle the breakpoint.
+
+
+# Press the green button in the gutter to run the script.
+if __name__ == '__main__':
+    print_hi('PyCharm')
+
+# See PyCharm help at https://www.jetbrains.com/help/pycharm/

+ 42 - 0
two_sum.py

@@ -0,0 +1,42 @@
+import pytest
+
+
+def twoSum(nums, target):
+    lens = len(nums)
+    j=-1
+    for i in range(lens):
+        if (target - nums[i]) in nums:
+            # 如果num2=num1,且nums中只出现了一次,说明找到是num1本身。
+            if (nums.count(target - nums[i]) == 1) & (target - nums[i] == nums[i]):
+                continue
+            else:
+                # index(x,i+1)是从num1后的序列后找num2
+                j = nums.index(target - nums[i],i+1)
+                break
+    if j>0:
+        return [i,j]
+    else:
+        return []
+
+#
+# def twoSum(nums, target):
+#     hashmap={}
+#     for ind,num in enumerate(nums):
+#         hashmap[num] = ind
+#     for i,num in enumerate(nums):
+#         j = hashmap.get(target - num)
+#         if j is not None and i!=j:
+#             return [i,j]
+
+
+def test_case_1():
+    res = twoSum([2, 3, 1, 5, 8], 6)
+    expect = [2, 3]
+    assert expect == res
+
+
+
+
+
+
+