二叉樹的鏡像
時間:2019年6月21日09:24:27
難度:簡單
編號:16
進(jìn)度:1/5 25/52
語言:java
類型:遞歸,二叉樹
題目來源:??途W(wǎng)
思路:最簡單的題了,就不多說了。有個小坑,當(dāng)節(jié)點(diǎn)為null的時候,返回值應(yīng)該是return ; 不要寫成 return null;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public void Mirror(TreeNode root) {
TreeNode temp = null;
if(root == null){
return ;
}
temp = root.left;
root.left = root.right;
root.right = temp;
if(root.left!=null){
Mirror(root.left);
}
if(root.right!=null){
Mirror(root.right);
}
}
}
運(yùn)行時間:28ms
占用內(nèi)存:9552k
構(gòu)建乘積數(shù)組
時間:2019年6月21日09:56:09
難度:簡單
編號:17
進(jìn)度:2/5 25/52
語言:c++
類型:數(shù)組
題目來源:??途W(wǎng)
思路:這題可以用動態(tài)規(guī)劃的思路去做;
這里把B數(shù)組看成兩個部分,
B[i] = B[0]+B[1]+...+B[i-1] + B[i+1]+....+B[n-1]
畫出矩陣圖可知,B數(shù)組組成了兩個三角形 ,前半部分是一個上三角,后半部分是一個下三角
前半部分從前往后相乘
后半部分從后往前相乘
class Solution {
public:
vector<int> multiply(const vector<int>& A) {
int n = A.size();
vector<int> b(n);
b[0] = 1;
for(int i =1; i<n;i++){
b[i] = b[i-1]*A[i-1];
}
int temp = 1;
for(int i = n-2;i>=0;i--){
temp *=A[i+1];
b[i] *=temp;
}
return b;
}
};
調(diào)整數(shù)組順序使奇數(shù)位于偶數(shù)前面
時間:2019年6月21日10:51:25
難度:簡單
編號:18
進(jìn)度:3/5 25/52
語言:c++
類型:數(shù)組
題目來源:??途W(wǎng)
思路:用空間換時間,很簡單
# -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
# 空間換時間
# 時間O(n)
# 空間O(n)
odd,even =[],[]
for each in array:
if each%2 ==0:
even.append(each)
else:
odd.append(each)
return odd+even
矩形覆蓋
時間:2019年06月22日11:30:37
難度:簡單
編號:19
進(jìn)度:4/5 25/52
語言:python
類型:斐波那契數(shù)列,腦筋急轉(zhuǎn)彎
題目來源:??途W(wǎng)
思路:斐波那契數(shù)列
時間復(fù)雜度:
空間復(fù)雜度:
# -*- coding:utf-8 -*-
class Solution:
def rectCover(self, number):
# write code here
if number<=1:
return number
a,b = 1,1
for each in range(1,number):
a,b = b,a+b
return b
119. 楊輝三角 II
時間:2019年6月22日14:56:39
難度:簡單
編號:20
進(jìn)度:5/5 25/52
語言:python
類型:楊輝三角,迭代
題目來源:leetcode
思路:迭代即可
時間復(fù)雜度:
空間復(fù)雜度:
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
if rowIndex == 0:
return [1]
if rowIndex ==1:
return [1,1]
ans = [1,1]
data = [1]
for index in range(2,rowIndex+1):
data = [1]
for i in range(0,index-1):
data.append(ans[i]+ans[i+1])
data.append(1)
ans = data
return data
118. 楊輝三角
class Solution:
def generate(self, rowIndex: int) -> List[List[int]]:
if rowIndex == 0:
return [[1]]
ans = [1,1]
data = [1]
res = [[1],[1,1]]
if rowIndex ==1:
return res
for index in range(2,rowIndex):
data = [1]
for i in range(0,index-1):
data.append(ans[i]+ans[i+1])
data.append(1)
ans = data
res.append(data)
return res