leetcode题解日练--2016.6.23

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

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

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

今日题目:1、从有序数组中删除元素;2、二叉树的层次遍历;3、阶乘后面0的数目;4、杨辉三角II;5、回文数

26. Remove Duplicates from Sorted Array | Difficulty: Easy

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.
题意:给定一个排序好的数组,去掉重复元素,不能利用额外的空间。
思路:
既然已经排好序了,那么就很简单了,从下标为1的元素开始判断,如果当前元素和前面一个元素不想等,就计数一次,同时进行一次赋值操作,若相等则直接访问下一个值
代码:
C++

class Solution {
public:int removeDuplicates(vector<int>& nums) {int n = nums.size();if(n<2) return n;int res=1;for(int i=1;i<nums.size();i++){if(nums[i]!=nums[i-1])nums[res++] = nums[i];}return res;}
};

结果:32ms

102. Binary Tree Level Order Traversal | Difficulty: Easy

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
题意:从上到下,从左到右遍历一棵树。
与6.21日做的107题基本一致,只是遍历的顺序不同而已。
http://blog.csdn.net/sysu_cis/article/details/51730192
思路:
直接附上代码
c++

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     TreeNode *left;*     TreeNode *right;*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/
class Solution {
public:vector<vector<int>> res;void DFS(TreeNode*root,int level){if(!root) return;if(res.size()==level)res.push_back(vector<int>());res[level].push_back(root->val);DFS(root->left,level+1);DFS(root->right,level+1);}vector<vector<int>> levelOrder(TreeNode* root) {DFS(root,0);return vector<vector<int>>(res.begin(),res.end());}
};

结果:8ms
2、BFS写法
第二次刷代码

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     TreeNode *left;*     TreeNode *right;*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/
class Solution {
public:vector<vector<int>> levelOrder(TreeNode* root) {vector<vector<int > >res;if(root==NULL)  return res;queue<TreeNode*>nodes;nodes.push(root);while(!nodes.empty()){int size = nodes.size();vector<int>path;for(int i=0;i<size;i++){TreeNode *cur = nodes.front();nodes.pop();path.push_back(cur->val);if(cur->left)   nodes.push(cur->left);if(cur->right)   nodes.push(cur->right);}res.push_back(path);}return res;}
};

结果:8ms

172. Factorial Trailing Zeroes | Difficulty: Easy

Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity.

题意:给出一个整数n,找到n!最后有几位0。
思路:当a>b的时候,a!后面0的数目一定大于等于b!后面0的数目。那什么时候出现第一个0呢,n=5,第二个0出现在n=10,第三个n=15,那么很显然只有2乘以5才会产生一个10,岁所有数据进行因子的分解,2的数目必定多于5的数目,因此只要计算n!中包含多少个因子5就可以了。
后来想当然的写出计算5个数的式子,发现结果并不对,思考了下发现产生多个5的情况是5的次方,引用https://leetcode.com/discuss/19847/simple-c-c-solution-with-detailed-explaination的例子
Example Three

By given number 4617.

5^1 : 4617 ÷ 5 = 923.4, so we get 923 factors of 5

5^2 : 4617 ÷ 25 = 184.68, so we get 184 additional factors of 5

5^3 : 4617 ÷ 125 = 36.936, so we get 36 additional factors of 5

5^4 : 4617 ÷ 625 = 7.3872, so we get 7 additional factors of 5

5^5 : 4617 ÷ 3125 = 1.47744, so we get 1 more factor of 5

5^6 : 4617 ÷ 15625 = 0.295488, which is less than 1, so stop here.

Then 4617! has 923 + 184 + 36 + 7 + 1 = 1151 trailing zeroes.
代码:
C++

int trailingZeroes(int n) {int result = 0;for(long long i=5; n/i>0; i*=5){result += (n/i);}return result;
}

结果:7ms

119. Pascal’s Triangle II | Difficulty: Easy

Given an index k, return the kth row of the Pascal’s triangle.

For example, given k = 3,
Return [1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?
题意:杨辉三角的一个变形,之前是给出n写出前n行的杨辉三角,现在是给出n写出第n行的杨辉三角。
思路:
首先将杨辉三角这样来看。
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
找杨辉三角的规律,首先,两端元素都是1,第0行可以认为既是左边又是右边。
除了两端元素之外的其他每个元素等于它上面一个元素和上面左边元素。i表示行号,j表示列号。
r[i][j] = r[i-1][j-1]+r[i-1][j]
杨辉三角1的代码:

class Solution {
public:vector<vector<int> > generate(int numRows) {vector<vector<int>> res(numRows);for (int i = 0; i < numRows; i++) {res[i].resize(i + 1);for(int j=0;j<=i;j++){if(j==0||j==i)res[i][j] = 1;elseres[i][j] = res[i-1][j-1]+res[i-1][j];}}return res;}
};

结果:4ms
此时,我们当然可以用一样的代码,只不过返回res[rowIndex]而已,但是显然复杂度高了。
因为第i行只与第i-1行有关,所以只需要记录一下前面一行的数据就可以了。这个时候空间复杂度是O(2*k)

class Solution {
public:vector<int> getRow(int rowIndex) {vector<int>cur,pre;if(rowIndex<=1){while(rowIndex-->=0)cur.push_back(1);return cur;}pre.push_back(1);pre.push_back(1);for(int i=2;i<=rowIndex;i++){cur.clear();for(int j=0;j<=i;j++){if(j==0||j==i)cur.push_back(1);elsecur.push_back(pre[j-1]+pre[j]);}pre = cur;}return cur;}
};

结果:3ms

那么还能不能有更低的空间呢?答案是肯定的,但是这需要我们找到每一行的一个通项公式。
但是我没找到,参考了https://leetcode.com/discuss/8364/here-is-my-brief-o-k-solution的solution。

class Solution {
public:vector<int> getRow(int rowIndex) {vector<int> A(rowIndex+1, 0);A[0] = 1;for(int i=1; i<rowIndex+1; i++)for(int j=i; j>=1; j--)A[j] += A[j-1];return A;}
};

暂时马克,说不定哪天突然就明白了。
2016.08.31明白了
第二次刷代码

class Solution {
public:vector<int> getRow(int rowIndex) {vector<int>res(rowIndex+1,0);res[0]=1;for(int i=1;i<=rowIndex;i++){for(int j=i;j>=0;j--)res[j]+=res[j-1];}return res;}
};

结果:2ms

9. Palindrome Number | Difficulty: Easy

Determine whether an integer is a palindrome. Do this without extra space.
题意:判断一个数字是否是回文数
思路:
是整型,因为不允许考虑额外的空间,因此可以将一个数分开两半来看。当数是奇数位的时候,每次原始数字提出最低位作为新数字的最高位,直到新数比原先的数位数多为止。最后判断新数/10和原数是否一样。如果数字是偶数位的情况下,只需要循环到新数大于旧数,如果是回文数字那么终止的时候两个数一定相等,反之不是回文数。

class Solution {
public:bool isPalindrome(int x) {if(x<0||(x!=0&&x%10==0)) return false;int sum = 0;while(x>sum){sum =sum*10+x%10;x /=10;}return (x==sum)||(sum/10==x);}
};

结果:76ms

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



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

相关文章

龙蜥操作系统Anolis OS-23.x安装配置图解教程(保姆级)

《龙蜥操作系统AnolisOS-23.x安装配置图解教程(保姆级)》:本文主要介绍了安装和配置AnolisOS23.2系统,包括分区、软件选择、设置root密码、网络配置、主机名设置和禁用SELinux的步骤,详细内容请阅读本文,希望能对你有所帮助... ‌AnolisOS‌是由阿里云推出的开源操作系统,旨

哈希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

安卓链接正常显示,ios#符被转义%23导致链接访问404

原因分析: url中含有特殊字符 中文未编码 都有可能导致URL转换失败,所以需要对url编码处理  如下: guard let allowUrl = webUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {return} 后面发现当url中有#号时,会被误伤转义为%23,导致链接无法访问

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

【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就行了。 这样