leetcode题解日练--2016.6.21

2024-03-06 10:48
文章标签 leetcode 21 题解 日练 2016.6

本文主要是介绍leetcode题解日练--2016.6.21,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

编程日记,尽量保证每天至少3道leetcode题,仅此记录学习的一些题目答案与思路,尽量用多种思路来分析解决问题,不足之处还望指出。

今日题目:1、二叉树的自底向上遍历;2、判定是否平衡树;3、去除元素;4、加1

107. Binary Tree Level Order Traversal II | Difficulty: Easy

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

110. Balanced Binary Tree | Difficulty: Easy

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;        }
};

27. Remove Element | Difficulty: Easy

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

66. Plus One | Difficulty: Easy

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))]

这篇关于leetcode题解日练--2016.6.21的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/779816

相关文章

哈希leetcode-1

目录 1前言 2.例题  2.1两数之和 2.2判断是否互为字符重排 2.3存在重复元素1 2.4存在重复元素2 2.5字母异位词分组 1前言 哈希表主要是适合于快速查找某个元素(O(1)) 当我们要频繁的查找某个元素,第一哈希表O(1),第二,二分O(log n) 一般可以分为语言自带的容器哈希和用数组模拟的简易哈希。 最简单的比如数组模拟字符存储,只要开26个c

leetcode-24Swap Nodes in Pairs

带头结点。 /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/public class Solution {public ListNode swapPairs(L

leetcode-23Merge k Sorted Lists

带头结点。 /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/public class Solution {public ListNode mergeKLists

C++ | Leetcode C++题解之第393题UTF-8编码验证

题目: 题解: class Solution {public:static const int MASK1 = 1 << 7;static const int MASK2 = (1 << 7) + (1 << 6);bool isValid(int num) {return (num & MASK2) == MASK1;}int getBytes(int num) {if ((num &

【每日一题】LeetCode 2181.合并零之间的节点(链表、模拟)

【每日一题】LeetCode 2181.合并零之间的节点(链表、模拟) 题目描述 给定一个链表,链表中的每个节点代表一个整数。链表中的整数由 0 分隔开,表示不同的区间。链表的开始和结束节点的值都为 0。任务是将每两个相邻的 0 之间的所有节点合并成一个节点,新节点的值为原区间内所有节点值的和。合并后,需要移除所有的 0,并返回修改后的链表头节点。 思路分析 初始化:创建一个虚拟头节点

C语言 | Leetcode C语言题解之第393题UTF-8编码验证

题目: 题解: static const int MASK1 = 1 << 7;static const int MASK2 = (1 << 7) + (1 << 6);bool isValid(int num) {return (num & MASK2) == MASK1;}int getBytes(int num) {if ((num & MASK1) == 0) {return

【LabVIEW学习篇 - 21】:DLL与API的调用

文章目录 DLL与API调用DLLAPIDLL的调用 DLL与API调用 LabVIEW虽然已经足够强大,但不同的语言在不同领域都有着自己的优势,为了强强联合,LabVIEW提供了强大的外部程序接口能力,包括DLL、CIN(C语言接口)、ActiveX、.NET、MATLAB等等。通过DLL可以使用户很方便地调用C、C++、C#、VB等编程语言写的程序以及windows自带的大

【JavaScript】LeetCode:16-20

文章目录 16 无重复字符的最长字串17 找到字符串中所有字母异位词18 和为K的子数组19 滑动窗口最大值20 最小覆盖字串 16 无重复字符的最长字串 滑动窗口 + 哈希表这里用哈希集合Set()实现。左指针i,右指针j,从头遍历数组,若j指针指向的元素不在set中,则加入该元素,否则更新结果res,删除集合中i指针指向的元素,进入下一轮循环。 /*** @param

C - Word Ladder题解

C - Word Ladder 题解 解题思路: 先输入两个字符串S 和t 然后在S和T中寻找有多少个字符不同的个数(也就是需要变换多少次) 开始替换时: tips: 字符串下标以0开始 我们定义两个变量a和b,用于记录当前遍历到的字符 首先是判断:如果这时a已经==b了,那么就跳过,不用管; 如果a大于b的话:那么我们就让s中的第i项替换成b,接着就直接输出S就行了。 这样

LeetCode:64. 最大正方形 动态规划 时间复杂度O(nm)

64. 最大正方形 题目链接 题目描述 给定一个由 0 和 1 组成的二维矩阵,找出只包含 1 的最大正方形,并返回其面积。 示例1: 输入: 1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0输出: 4 示例2: 输入: 0 1 1 0 01 1 1 1 11 1 1 1 11 1 1 1 1输出: 9 解题思路 这道题的思路是使用动态规划