Skip to content

Commit 59bb790

Browse files
committed
first commit
0 parents  commit 59bb790

20 files changed

+822
-0
lines changed

100_same_tree.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""
2+
3+
Given two binary trees, write a function to check if they are equal or not.
4+
5+
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
6+
7+
"""
8+
9+
"""my solution
10+
采用中序遍历的方式
11+
"""
12+
13+
# Definition for a binary tree node.
14+
# class TreeNode(object):
15+
# def __init__(self, x):
16+
# self.val = x
17+
# self.left = None
18+
# self.right = None
19+
20+
class Solution(object):
21+
def isSameTree(self, p, q):
22+
"""
23+
:type p: TreeNode
24+
:type q: TreeNode
25+
:rtype: bool
26+
"""
27+
28+
if p != None and q != None:
29+
if self.isSameTree(p.left, q.left) and p.val == q.val and self.isSameTree(p.right, q.right):
30+
return True
31+
else:
32+
return False
33+
else:
34+
if p == None and q == None:
35+
return True
36+
else:
37+
return False
38+
39+
40+
"""more simple way"""
41+
def isSameTree(self, p, q):
42+
if p and q:
43+
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
44+
return p is q

14_longgest_common_prefix.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""
2+
3+
Write a function to find the longest common prefix string amongst an array of strings.
4+
5+
"""
6+
7+
8+
class Solution(object):
9+
def longestCommonPrefix(self, strs):
10+
"""
11+
:type strs: List[str]
12+
:rtype: str
13+
"""
14+
if len(strs) == 0:
15+
return ''
16+
cpre = strs[0]
17+
for onestr in strs[1:]:
18+
i = 0
19+
while i < len(cpre) and i < len(onestr) and cpre[i] == onestr[i]:
20+
i = i + 1
21+
cpre = cpre[:i]
22+
23+
return cpre
24+
25+
26+
"""an answer using zip"""
27+
28+
29+
def longestCommonPrefix(self, strs):
30+
"""
31+
:type strs: List[str]
32+
:rtype: str
33+
"""
34+
if not strs: return ''
35+
l = 0
36+
for cg in zip(*strs):
37+
if len(set(cg)) > 1:
38+
return strs[0][:l]
39+
l += 1
40+
return strs[0][:l]

1_two_sum.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""
2+
3+
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
4+
5+
You may assume that each input would have exactly one solution, and you may not use the same element twice.
6+
7+
Example:
8+
Given nums = [2, 7, 11, 15], target = 9,
9+
10+
Because nums[0] + nums[1] = 2 + 7 = 9,
11+
return [0, 1].
12+
13+
"""
14+
15+
"""my solution
16+
首先创建一个字典,用于保存已经遍历过的元素以及他们在字典中的位置
17+
如果差值在字典中,则返回字典中的索引值以及该元素的索引值
18+
如果差值不再字典中,将该元素加入字典
19+
"""
20+
21+
22+
class Solution:
23+
def twoSum(self, nums, target):
24+
"""
25+
:type nums: List[int]
26+
:type target: int
27+
:rtype: List[int]
28+
"""
29+
num_dict = dict()
30+
for index, value in enumerate(nums):
31+
sub = target - value
32+
if sub in num_dict.keys():
33+
return [num_dict[sub], index]
34+
else:
35+
num_dict[value] = index
36+
37+
return []
38+
39+
40+
"""标准答案1
41+
跟我的思路差不多,是把差值存入字典中
42+
而且考虑了nums长度小于1的情况
43+
"""
44+
45+
46+
def twoSum(self, nums, target):
47+
if len(nums) <= 1:
48+
return False
49+
buff_dict = {}
50+
for i in range(len(nums)):
51+
if nums[i] in buff_dict:
52+
return [buff_dict[nums[i]], i]
53+
else:
54+
buff_dict[target - nums[i]] = i

20_Valid_Parentheses.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""
2+
3+
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
4+
5+
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
6+
7+
"""
8+
9+
"""my solution
10+
使用一个栈,如果是前半部分就进栈,如果是后半部分就出栈 ,并测试是否匹配
11+
"""
12+
class Solution(object):
13+
def isValid(self, s):
14+
"""
15+
:type s: str
16+
:rtype: bool
17+
"""
18+
if len(s) % 2 != 0:
19+
return False
20+
stack = []
21+
push_list = ['(','[','{']
22+
pop_list = [')',']','}']
23+
for single_char in s:
24+
if single_char in push_list:
25+
stack.append(single_char)
26+
if single_char in pop_list:
27+
if single_char == ')':
28+
if len(stack)==0 or stack.pop() != '(':
29+
return False
30+
elif single_char ==']':
31+
if len(stack)==0 or stack.pop() != '[':
32+
return False
33+
elif single_char == '}':
34+
if len(stack)==0 or stack.pop() != '{':
35+
return False
36+
if len(stack) == 0:
37+
return True
38+
else:
39+
return False
40+
41+
"""前面我定义了两个list,其实可以定义成一个dict 最后的判断stack是否为空也可以写成一条语句"""
42+
class Solution:
43+
# @return a boolean
44+
def isValid(self, s):
45+
stack = []
46+
dict = {"]":"[", "}":"{", ")":"("}
47+
for char in s:
48+
if char in dict.values():
49+
stack.append(char)
50+
elif char in dict.keys():
51+
if stack == [] or dict[char] != stack.pop():
52+
return False
53+
else:
54+
return False
55+
return stack == []

21_Merge_Two_Sorted_Lists.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""
2+
3+
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
4+
5+
"""
6+
7+
8+
# Definition for singly-linked list.
9+
class ListNode(object):
10+
def __init__(self, x):
11+
self.val = x
12+
self.next = None
13+
14+
class Solution(object):
15+
def mergeTwoLists(self, l1, l2):
16+
"""
17+
:type l1: ListNode
18+
:type l2: ListNode
19+
:rtype: ListNode
20+
"""
21+
head = cur = ListNode(0)
22+
while l1 and l2:
23+
if l1.val > l2.val:
24+
cur.next = l2
25+
l2 = l2.next
26+
else:
27+
cur.next = l1
28+
l1 = l1.next
29+
cur = cur.next
30+
"""or 返回第一个为真的值"""
31+
cur.next = l1 or l2
32+
return head.next
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
"""
2+
3+
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
4+
5+
Do not allocate extra space for another array, you must do this in place with constant memory.
6+
7+
For example,
8+
Given input array nums = [1,1,2],
9+
10+
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.
11+
12+
"""
13+
"""my solution
14+
这里要注意一个额外的细节,那就是要求把不同的元素放到数组的前几位,不能简单的返回一个count值
15+
"""
16+
17+
18+
class Solution(object):
19+
def removeDuplicates(self, nums):
20+
"""
21+
:type nums: List[int]
22+
:rtype: int
23+
"""
24+
if nums == []:
25+
return 0
26+
count = 1
27+
cur = nums[0]
28+
for i in nums:
29+
if i == cur:
30+
continue
31+
else:
32+
cur = i
33+
nums[count] = i
34+
count += 1
35+
36+
return count
37+
38+
39+
"""
40+
other solutions
41+
"""
42+
43+
class Solution:
44+
# @param a list of integers
45+
# @return an integer
46+
def removeDuplicates(self, A):
47+
if not A:
48+
return 0
49+
50+
newTail = 0
51+
52+
for i in range(1, len(A)):
53+
if A[i] != A[newTail]:
54+
newTail += 1
55+
A[newTail] = A[i]
56+
57+
return newTail + 1

27_Remove_Element.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""
2+
3+
Given an array and a value, remove all instances of that value in place and return the new length.
4+
5+
Do not allocate extra space for another array, you must do this in place with constant memory.
6+
7+
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
8+
9+
Example:
10+
Given input array nums = [3,2,2,3], val = 3
11+
12+
Your function should return length = 2, with the first two elements of nums being 2.
13+
14+
15+
16+
"""
17+
18+
""" my solution
19+
借鉴26题的思路,直接遍历,由于前面的已经遍历过,可以直接替换屌元素的值
20+
"""
21+
22+
23+
class Solution(object):
24+
def removeElement(self, nums, val):
25+
"""
26+
:type nums: List[int]
27+
:type val: int
28+
:rtype: int
29+
"""
30+
index = 0
31+
for i in range(0, len(nums)):
32+
if nums[i] != val:
33+
nums[index] = nums[i]
34+
index = index + 1
35+
36+
return index
37+
38+
39+
"""other solution
40+
交换的思路
41+
"""

0 commit comments

Comments
 (0)