Squares of a Sorted Array (Leetcode 977)
to solve this problem, the eaist way would be iterate trough the input list and then add the square of every elements into the list and then implement a binary search, which would give a time complexity of N(n+nlog(n)). However, a more optimal way would be implement the two pointers: becuase the array is ordered. Big numbers will come from two ends and the small will come from the center (or near zero). We can use two pointers to run from sides to center and add the biggest value into a array. This only requires one iteration thus the complexity is O(n).
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
i, j, k = 0, len(nums)-1, len(nums)-1
result = [0]*len(nums)
while(i<=j):
ls = nums[i]**2
rs = nums[j]**2
if ls>=rs:
result[k] = ls
i += 1
else:
result[k] = rs
j -= 1
k -= 1
return result
Minimum Size Subarray Sum (Leetcode 209)
to solve this question, the most straightforward method is to iterate every starting point and then iterate and find the smallest length. This will give us a comlexity of N(n^2). A better way would be use two pointers to implement a slide window. The fast pointer find a combination big enough, the left subtract and reduce the array size to find the mininum.
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
the_sum = 0
res = float('inf')
j = 0
for i in range(len(nums)):
the_sum += nums[i]
while the_sum >= target:
res = min(i-j+1,res)
the_sum -= nums[j]
j += 1
if res == float('inf'):
return 0
return res
Spiral Matrix II (Leetcode 59)
To solve this problem, we need to be clear about the start and end boundry. The filling will circulate n//2 times for even number and n//2 + filling the center for odd number. 1. initialize an array that has 1 to n**2. Then define start x,y, loop number n//2+1, offset for the blank at the end. Finally filling the square layer by layer clockwise and then update the parameters. Time complexity is N(n**2)
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
nums = [[0] * n for _ in range(n)]
x,y = 0,0
offset = 1
count = 1
for i in range(n//2 + 1):
for j in range(x,n-offset):
nums[y][j] = count
count += 1
for j in range(y,n-offset):
nums[j][n-offset] = count
count += 1
for j in range(n-offset,x,-1):
nums[n-offset][j] = count
count += 1
for j in range(n-offset,y,-1):
nums[j][x] = count
count += 1
x += 1
y += 1
offset += 1
if n%2 != 0:
nums[n//2][n//2] = count
return nums