Skip to content

Commit 1d0d594

Browse files
committed
97python
1 parent 37b4b95 commit 1d0d594

File tree

5 files changed

+344
-23
lines changed

5 files changed

+344
-23
lines changed

Python/binary-search.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
'''
2+
3+
Gven a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1.
4+
5+
6+
Example 1:
7+
8+
Input: nums = [-1,0,3,5,9,12], target = 9
9+
Output: 4
10+
Explanation: 9 exists in nums and its index is 4
11+
12+
Example 2:
13+
14+
Input: nums = [-1,0,3,5,9,12], target = 2
15+
Output: -1
16+
Explanation: 2 does not exist in nums so return -1
17+
18+
19+
Note:
20+
21+
You may assume that all elements in nums are unique.
22+
n will be in the range [1, 10000].
23+
The value of each element in nums will be in the range [-9999, 9999].
24+
25+
26+
'''
27+
28+
29+
class Solution:
30+
def search(self, nums, target):
31+
"""
32+
:type nums: List[int]
33+
:type target: int
34+
:rtype: int
35+
"""
36+
# Approach one
37+
# l,r = 0 , len(nums)-1
38+
# while l <= r:
39+
# mid = (l + r) // 2
40+
# if nums[mid] == target: return mid
41+
# if l == r : break
42+
# if nums[mid] < target:
43+
# l = mid + 1
44+
# else :
45+
# r = mid
46+
# return -1
47+
48+
# Approach one
49+
l,r = 0 , len(nums)-1
50+
while l <= r:
51+
mid = (l + r) // 2
52+
if nums[mid] == target: return mid
53+
if nums[mid] < target:
54+
l = mid + 1
55+
else :
56+
r = mid - 1
57+
return -1

Python/design-circular-queue.py

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
'''
2+
3+
Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer".
4+
5+
One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.
6+
7+
Your implementation should support following operations:
8+
9+
MyCircularQueue(k): Constructor, set the size of the queue to be k.
10+
Front: Get the front item from the queue. If the queue is empty, return -1.
11+
Rear: Get the last item from the queue. If the queue is empty, return -1.
12+
enQueue(value): Insert an element into the circular queue. Return true if the operation is successful.
13+
deQueue(): Delete an element from the circular queue. Return true if the operation is successful.
14+
isEmpty(): Checks whether the circular queue is empty or not.
15+
isFull(): Checks whether the circular queue is full or not.
16+
17+
18+
Example:
19+
20+
MyCircularQueue circularQueue = new MyCircularQueue(3); // set the size to be 3
21+
circularQueue.enQueue(1); // return true
22+
circularQueue.enQueue(2); // return true
23+
circularQueue.enQueue(3); // return true
24+
circularQueue.enQueue(4); // return false, the queue is full
25+
circularQueue.Rear(); // return 3
26+
circularQueue.isFull(); // return true
27+
circularQueue.deQueue(); // return true
28+
circularQueue.enQueue(4); // return true
29+
circularQueue.Rear(); // return 4
30+
31+
Note:
32+
33+
All values will be in the range of [0, 1000].
34+
The number of operations will be in the range of [1, 1000].
35+
Please do not use the built-in Queue library.
36+
37+
'''
38+
39+
40+
41+
class MyCircularQueue:
42+
43+
def __init__(self, k):
44+
"""
45+
Initialize your data structure here. Set the size of the queue to be k.
46+
:type k: int
47+
"""
48+
self.size = k
49+
self.queue = k * [-1]
50+
self.head = -1
51+
self.rear = -1
52+
53+
54+
55+
def enQueue(self, value):
56+
"""
57+
Insert an element into the circular queue. Return true if the operation is successful.
58+
:type value: int
59+
:rtype: bool
60+
"""
61+
if self.isFull(): # 注意什么时候不能继续入栈
62+
return False
63+
if self.isEmpty():
64+
self.head = 0
65+
self.rear = (self.rear + 1) % self.size
66+
self.queue[self.rear] = value
67+
return True
68+
69+
def deQueue(self):
70+
"""
71+
Delete an element from the circular queue. Return true if the operation is successful.
72+
:rtype: bool
73+
"""
74+
if self.isEmpty():
75+
return False
76+
if self.head == self.rear: # 出栈不需要真的删除元素,只需要改变头尾指针
77+
self.head = -1 # 首尾指针指到相同元素,且不为-1,此时必然仅有一个元素
78+
self.rear = -1
79+
return True
80+
self.head = (self.head + 1) % self.size
81+
return True
82+
83+
84+
def Front(self):
85+
"""
86+
Get the front item from the queue.
87+
:rtype: int
88+
"""
89+
return self.queue[self.head] if not self.isEmpty() else -1
90+
91+
92+
def Rear(self):
93+
"""
94+
Get the last item from the queue.
95+
:rtype: int
96+
"""
97+
return self.queue[self.rear] if not self.isEmpty() else -1
98+
99+
100+
def isEmpty(self):
101+
"""
102+
Checks whether the circular queue is empty or not.
103+
:rtype: bool
104+
"""
105+
return self.head == -1
106+
107+
108+
def isFull(self):
109+
"""
110+
Checks whether the circular queue is full or not.
111+
:rtype: bool
112+
"""
113+
return (self.rear + 1) % self.size == self.head # 考虑到循环队列,所以去要取整
114+
115+
116+
117+
# Your MyCircularQueue object will be instantiated and called as such:
118+
# obj = MyCircularQueue(k)
119+
# param_1 = obj.enQueue(value)
120+
# param_2 = obj.deQueue()
121+
# param_3 = obj.Front()
122+
# param_4 = obj.Rear()
123+
# param_5 = obj.isEmpty()
124+
# param_6 = obj.isFull()

Python/merge-sorted-array.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
'''
2+
3+
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
4+
5+
Note:
6+
7+
The number of elements initialized in nums1 and nums2 are m and n respectively.
8+
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
9+
Example:
10+
11+
Input:
12+
nums1 = [1,2,3,0,0,0], m = 3
13+
nums2 = [2,5,6], n = 3
14+
15+
Output: [1,2,2,3,5,6]
16+
17+
18+
'''
19+
20+
21+
class Solution:
22+
def merge(self, nums1, m, nums2, n):
23+
"""
24+
:type nums1: List[int]
25+
:type m: int
26+
:type nums2: List[int]
27+
:type n: int
28+
:rtype: void Do not return anything, modify nums1 in-place instead.
29+
"""
30+
# Approach one 效率低
31+
# a = m - 1
32+
# b = n - 1
33+
# k = m+n-1
34+
# if n > 0: # List[int] == []
35+
# print(nums1,m,nums2,n)
36+
# if m == 0: nums1[:] = nums2 # nums1 被赋值必须加上 [:]
37+
# else:
38+
# while k >= 0:
39+
# if nums1[a] >= nums2[b]:
40+
# nums1[k] = nums1[a]
41+
# if a == 0 and nums2[b] != -10000:
42+
# nums1[0] = -10000
43+
# else:
44+
# a -= 1
45+
# else:
46+
# nums1[k] = nums2[b]
47+
# if b == 0 and nums1[a] != -10000:
48+
# nums2[0] = -10000
49+
# else:
50+
# b -= 1
51+
# k -= 1
52+
53+
# Approach two
54+
nums1[m:] = nums2
55+
nums1.sort()

Python/perfect-squares.py

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
'''
2+
3+
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
4+
5+
Example 1:
6+
7+
Input: n = 12
8+
Output: 3
9+
Explanation: 12 = 4 + 4 + 4.
10+
Example 2:
11+
12+
Input: n = 13
13+
Output: 2
14+
Explanation: 13 = 4 + 9.
15+
16+
17+
'''
18+
19+
20+
21+
22+
23+
24+
class Solution:
25+
def numSquares(self, n):
26+
"""
27+
:type n: int
28+
:rtype: int
29+
"""
30+
31+
# Approach one 【失败】 贪心算法不适用,大的数不一定会入选
32+
# res = [i ** 2 for i in range(1,n//2+1) if i ** 2 <= n]
33+
# print(res)
34+
# tmp_ans = count = 0
35+
# ans = []
36+
# while len(res) > 1:
37+
# point = -1
38+
# while count != n:
39+
# if res[point] <= n - count:
40+
# count += res[point]
41+
# tmp_ans += 1
42+
# else:
43+
# point -= 1
44+
# ans.append(tmp_ans)
45+
# tmp_ans = count = 0
46+
# del res[-1]
47+
# return min(ans) if ans else n
48+
49+
50+
# Approach two 利用队列和BFS,最先搜索到的结果一定是最短的。 队列中存储(位置,步数) ,效率比较低。
51+
# q = [[n, 0]]
52+
# visited = [False for _ in range(n + 1)]
53+
# visited[n] = True
54+
# while any(q):
55+
# num, step = q.pop(0) # 出栈,被pop掉的元素将同时返回给两个变量
56+
# i = 1
57+
# tnum = num - i ** 2
58+
# while tnum >= 0: # 前进一步
59+
# if tnum == 0: return step + 1 # 最先到达0的一定是步数最少的
60+
# if not visited[tnum]:
61+
# q.append((tnum, step + 1))
62+
# visited[tnum] = True # 只添加没有遍历过的节点,减少计算量
63+
# i += 1
64+
# tnum = num - i ** 2
65+
66+
67+
68+
# Approach three
69+
# Lagrange 四平方定理: 任何一个正整数都可以表示成不超过四个整数的平方之和。
70+
# 也就是说,这个题目返回的答案只有1、2、3、4这四种可能。 我们可以将输入的数字除以4来大大减少计算量,并不改变答案
71+
# 一个数除以8的余数,如果余数为7, 则其必然由四个完全平方数组成
72+
# 然后检测是否可以将简化后的数拆分为两个完全平方数,否则一定由三个完全平方数组成。
73+
import math
74+
while n % 4 == 0: n = n // 4
75+
if n % 8 == 7: return 4
76+
if int(math.sqrt(n)) ** 2 == n: return 1
77+
i = 1
78+
while i*i <= n:
79+
j = math.sqrt(n - i*i)
80+
if int(j) == j: return 2
81+
i += 1
82+
return 3

0 commit comments

Comments
 (0)