Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Main #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions 1260. Shift 2D Grid/1260. Shift 2D Grid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""
Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.

In one shift operation:

Element at grid[i][j] moves to grid[i][j + 1].
Element at grid[i][n - 1] moves to grid[i + 1][0].
Element at grid[m - 1][n - 1] moves to grid[0][0].
Return the 2D grid after applying shift operation k times.



Example 1:


Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[9,1,2],[3,4,5],[6,7,8]]
Example 2:


Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]
Example 3:

Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9
Output: [[1,2,3],[4,5,6],[7,8,9]]


Constraints:

m == grid.length
n == grid[i].length
1 <= m <= 50
1 <= n <= 50
-1000 <= grid[i][j] <= 1000
0 <= k <= 100
"""
class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m,n = len(grid), len(grid[0])
k = k % (m*n)
temp = [grid[i][j] for i in range(m) for j in range(n)]
temp = temp[-k:] + temp[:-k]
result = []
for i in range(m):
result.append(temp[i*n:i*n+n])
return result
Original file line number Diff line number Diff line change
Expand Up @@ -20,26 +20,24 @@

Note that an empty tree is represented by NULL, therefore you would see the expected output (serialized tree format) as [], not null.
"""


# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return None
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root: return None
q = collections.deque()
q.append(root)
while q:
node = q.popleft()
if node.val == val:
return node
if node.left:
q.append(node.left)
if node.right:
elif node.val < val and node.right:
q.append(node.right)
else:
if node.left:
q.append(node.left)
return None