Day2: (Arrays)
Set Matrix Zeros Looked for answer on 16th July 2020
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
rows = []
columna = []
for i in range(0 , len(matrix)):
for j in range(0 , len(matrix[i])):
if matrix[i][j] == 0:
if i not in rows:
rows.append(i)
if j not in columna:
columna.append(j)
print (rows, columna)
for i in rows:
for j in range(0 , len(matrix[i])):
matrix[i][j] = 0
for i in columna:
for j in range(0 , len(matrix)):
matrix[j][i] = 0
2. Pascals Triangle Solved on: 17th July 2020
def generate(self, numRows: int) -> List[List[int]]:
l=[]
for i in range(numRows):
k=[]
for j in range(i+1):
if j==0 or j==i:
k.append(1)
else:
k.append(l[i-1][j-1] + l[i-1][j])
l.append(k)
return (l)
3. Next Permutation Learnt on 17th July 2020
def nextPermutation(self, arr: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
inverse_point = len(arr)-2
while (inverse_point >=0 and arr[inverse_point] >= arr[inverse_point+1]):
inverse_point = inverse_point-1
if (inverse_point < 0):
return []
for i in reversed(range(inverse_point, len(arr))):
if (arr[i] > arr[inverse_point]):
arr[i], arr[inverse_point] = arr[inverse_point], arr[i]
arr[inverse_point+1:] = reversed(arr[inverse_point+1:])
public:
void nextPermutation(vector<int>& nums) {
next_permutation(nums.begin(), nums.end());
}
Stock Buy and Sell Learnt on 24th July 2020
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if (len(prices) ==0):
return 0
min_price=prices[0]
max_profit=0
for item in prices:
profit = item - min_price
if profit > max_profit:
max_profit = profit
if item <= min_price:
min_price = item
return max_profit
int maxProfit(vector<int>& prices) {
int n=prices.size();
if (n==0) {
return 0;
}
int profit=0, max_profit=0, min_price=prices[0];
for (int i=0;i<n;i++) {
profit = prices[i]-min_price;
if (profit > max_profit) {
max_profit = profit;
}
if (prices[i] < min_price) {
min_price= prices[i];
}
}
return max_profit;
}
6. Rotate Matrix 90 degree Learnt on 27th July 2020
void rotate(vector<vector<int>>& matrix) {
// Transpose matrix
for (int i=0; i<size(matrix);i++) {
for (int j=i; j<size(matrix); j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
int n =size(matrix);
// Reverse row elements
for (int i=0;i<n;i++){
for (int j=0;j<n/2;j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[i][n-j-1];;
matrix[i][n-j-1] = temp;
}
}
}
Last updated
Was this helpful?