Tuesday, August 10, 2021

LintCode 496 · Toy Factory.py

"""
Your object will be instantiated and called as such:
ty = ToyFactory()
toy = ty.getToy(type)
toy.talk()
"""
# Simulation OOP
class Toy:
def talk(self):
raise NotImplementedError('This method should have implemented.')
class Dog(Toy):
# Write your code here
def talk(self):
print("Wow")
class Cat(Toy):
# Write your code here
def talk(self):
print("Meow")
class ToyFactory:
# @param {string} Type a string
# @return {Toy} Get object of the type
def getToy(self, type):
# Write your code here
if type == 'Dog':
return Dog()
elif type == 'Cat':
return Cat()
else:
return None

Sunday, August 8, 2021

LintCode 97 · Maximum Depth of Binary Tree.py

"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
# Approach #1 - DFS - T O(n), S O(h), with n being #OfNodes, h being the depth.
class Solution:
"""
@param root: The root of binary tree.
@return: An integer
"""
def maxDepth(self, root):
# write your code here
if root is None:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1

Saturday, August 7, 2021

LintCode 1178 · Student Attendance Record I.py

# Approach #1 - Simulation, String - T O(n), S O(1)
class Solution:
"""
@param s: a string
@return: whether the student could be rewarded according to his attendance record
"""
def checkRecord(self, s):
# Write your code here
# if As > 1 or consective Ls > 2, false, otherwise true
countA, countL = 0, 0
for ch in s:
if ch == 'A':
countA += 1
if countA > 1:
return False
countL = 0
elif ch == 'L':
countL += 1
if countL > 2:
return False
else:
countL = 0
return True

Friday, August 6, 2021

LintCode 1 · A + B Problem.py

class Solution:
"""
@param a: An integer
@param b: An integer
@return: The sum of a and b
"""
def aplusb(self, a, b):
# write your code here
return a + b

LintCode 39 · Recover Rotated Sorted Array.java

// Approach #1 - 3-way flipping - T O(n), S O(1)
public class Solution {
/**
* @param nums: An integer array
* @return: nothing
*/
public void recoverRotatedSortedArray(List<Integer> nums) {
// handle corner cases
if (nums == null || nums.size() == 0) {
return;
}
int n = nums.size();
int endingIndex = n - 1;
for (int i = 0; i < n - 1; i++) {
if (nums.get(i) > nums.get(i + 1)) {
endingIndex = i;
break;
}
}
// reverse left
reverse(nums, 0, endingIndex);
// reverse right
reverse(nums, endingIndex + 1, n - 1);
// reverse the whole thing
reverse(nums, 0, n - 1);
return;
}
private void reverse(List<Integer> nums, int left, int right) {
while (left < right) {
Integer tmp = nums.get(left);
nums.set(left, nums.get(right));
nums.set(right, tmp);
left++;
right--;
}
}
}