编程日记,尽量保证每天至少3道leetcode题,仅此记录学习的一些题目答案与思路,尽量用多种思路来分析解决问题,不足之处还望指出。
Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
Given a linked list, swap every two adjacent nodes and return its head.
题意:给定一棵二叉树,给出自底向上的遍历。
思路:
DFS搜索,从根节点开始,访问根节点并依次对其左右节点进行搜索,每一层用一个vector来存储。
代码:
C++
class Solution {
public:
//DFS搜索,对于每一层的元素,创建一个vecto用来存节点的值
vector<vector<int> > res;
void DFS(TreeNode* root,int level)
{
if (root==NULL) return;
if(level==res.size())
res.push_back(vector<int>());
res[level].push_back(root->val);
DFS(root->left,level+1);
DFS(root->right,level+1);
}
vector<vector<int> > levelOrderBottom(TreeNode *root) {
DFS(root,0);
return vector<vector<int>> (res.rbegin(),res.rend());
}
};
结果:4ms
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
题意:判断一棵树是否是平衡树,平衡树的定义是每个节点的子树高度相差不会大于1.
思路:
1、平衡树的定义是每个节点的子树高度相差不会超过1,那么我们可以顺着这个思路,从顶向下遍历,首先根节点必须满足左右子数高度差<=1,其次还需要根节点的左右节点各自满足平衡树的性质。因此,不难想到,用一个递归的思想就可以实现,代码如下:
c++
class Solution {
public:
int Depth(TreeNode* root){
if (root==NULL) return 0;
if (root->left==NULL && root-right==NULL)
return 1;
return max(Depth(root->left)+Depth(root->right))+1;
}
bool isBalanced(TreeNode* root) {
if(root==NULL) return true;
int left=depth(root->left);
int right=depth(root->right);
return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
};
结果:16ms
2、上述思路很容易理解,也很直观,后面参考了Discuss的一个Solution,其实这里也能用DFS的思想。之前,我们要判断根节点时候平衡的做法是什么?是根据根节点的左节点和右节点是否均满足平衡条件,但是为了计算左节点,又要递归的调用一次左节点的左节点和右节点,这样每个节点都需要调用一次求深度的函数,每次求深度复杂度为O(logN),整体复杂度是O(NlogN),最坏情况O(N^2)。
那如果我们从下往上求呢,在判断左右子树是否平衡的过程中把深度计算出来,这样在对父结点进行平衡判断时就可以不用再重复计算左右子树的深度了。这个过程就相当于后序遍历,复杂度为O(N)
class Solution {
public:
bool dfsDepth(TreeNode* root,int &height){
if(root==NULL) return true;
int left = 0,right = 0;
if(!dfsDepth(root->left,left)) return false;
if(!dfsDepth(root->right,right)) return false;
if(abs(left-right)>1) return false;
height = max(left,right)+1;
return true;
}
bool isBalanced(TreeNode* root) {
int height = 0;
bool result = dfsDepth(root,height);
return result;
}
};
Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
题意:返回数组中不为val的元素的个数。
思路:直接遍历一次找到不为val的,用一个count来计数,做一次交换即可。
代码:
C++
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int length = nums.size();
int count = 0;
for(int i=0;i<length;i++)
{
if(nums[i]!=val)
{
nums[count++] = nums[i];
}
}
return count;
}
};
结果:4ms
python
class Solution(object):
def removeElement(self, nums, val):
""" :type nums: List[int] :type val: int :rtype: int """
find_all = [idx for idx,e in enumerate(nums) if e!=val]
for i in range(len(find_all)):
nums[i] = nums[find_all[i]]
return len(find_all)
结果:48ms
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
思路:
1、模拟进位,只要碰到的位是9,那么就置为0,直到碰到一个不是9的位不再循环,返回。如果直到所有位都遍历了一次还没有返回,那么就说明最高位加到1了,这个时候将最高位置1同时末尾补零。
class Solution {
public:
vector<int> plusOne(vector<int>& digits)
{
int n = digits.size();
for (int i = n - 1; i >= 0; --i)
{
if (digits[i] == 9)
{
digits[i] = 0;
}
else
{
digits[i]++;
return digits;
}
}
digits[0] =1;
digits.push_back(0);
return digits;
}
};
结果:4ms
2、直接用python转成int然后加1之后转为字符串再转为列表
python
class Solution(object):
def plusOne(self, digits):
""" :type digits: List[int] :rtype: List[int] """
return [int(item) for item in\ list(str(int("".join(str(digit)for digit in digits))+1))]