leetcode day5
【242】Valid Anagram:
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
思路:看一个字符串是否是另一个字符串乱序形成的,这里面首先要考虑重复字母的情况,并且考虑时间空间复杂度,如果字符串很长的话。通过遍历其中一个字符串,逐个比较是否contains的方法不满足复杂度要求。所以考虑使用一个数组,索引是字母,值是这个字母出现的频率,两个字符串都指向这个数组,一个字符串增加频率,一个减小,然后for循环遍历这个数组,如果有非0值则返回FALSE
public class Solution {
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length()){
return false;
}
int[] count = new int[26];
for(int i=0;i<s.length();i++){
count[s.charAt(i)-'a']++;
count[t.charAt(i)-'a']--;
}
for(int i:count){
if(i!=0){
return false;
}
}
return true;
}
}
【235】Lowest Common Ancestor of a Binary Search Tree
可以先参考这篇博客:http://blog.csdn.net/beiyetengqing/article/details/7633651
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself
思路:找最近公共祖先,二叉树一般用的都是递归,什么时候停止递归,由于这是二叉搜索树,所以当左右结点当一个比根节点小,一个比根节点大就停止,也就是对应以下代码中判断条件中的第三种情况,另外再比较都比根节点小或者都比根节点大的时候,用Math.max()或者Math.min()更优雅
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null||p==null||q==null)return null;
if(Math.max(p.val,q.val)<root.val)return lowestCommonAncestor(root.left, p, q);//both lower than root
if(Math.min(p.val,q.val)>root.val)return lowestCommonAncestor(root.right, p, q);//both higher than root
return root;//the third cosition }
}
【191】Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.
思路:
求一个数中1的个数,也就是汉明距离,起初打算转换用string来处理,但是显然这样很慢,还有一种是按位处理,通过按位与1相与,然后记录次数,然后让这个数逻辑右移(算数右移和逻辑右移的区别:运算符“>>”执行算术右移,它使用最高位填充移位后左侧的空位,这样可以保证符号不变。右移的结果为:每移一位,第一个操作数被2除一次,移动的次数由第二个操作数确定。逻辑右移或叫无符号右移运算符“>>>“只对位进行操作,没有算术含义,它用0填充左侧的空位,不保证符号。)
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
String str = Integer.toBinaryString(n);//先把数转换成二进制
return (str.replace("0","").length());
}
}
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
return Integer.bitCount(n);//直接算一个整数的非0个数
}
}
public int hammingWeight(int n) {
int result = 0;
while (n != 0) {
if ((n & 1) == 1) {
result++;
}
n >>>= 1;
}
return result;
}
【169】Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
找超过数组长度一半的高频元素
思路:用字符串来处理永远不是最优的方法呀,字符串只能用来转换运算,不能实现逻辑功能。想象一下木桶原则的逆原则。
public class Solution {
public int majorityElement(int[] nums) {
int major = nums[0];//以第一个元素当探针
int count = 1;
for(int i=1;i<nums.length;i++){//注意从1开始,即第二个元素开始
if(count==0){//如果出现了和这个探针的元素频率相同的数字,则探针元素重新赋值,并且次数为1,接下来进行下一循环,不再执行后面 的判断
count = 1;
major = nums[i];
}else if(major ==nums[i]){
count++;
}else if(major != nums[i]){
count--;
}
}
return major;
/*String numsStr = Arrays.toString(nums);
int size = nums.length;
int[] freq = new int[size];
int max = 0;
for(int i=0;i<size;i++){
freq[i] = size-numsStr.replace(numsStr.charAt(i)+"","").length();
if(max<freq[i]) max = freq[i];
}
return max;*/
}
}
leetcode day5的更多相关文章
- LeetCode Day5——House Robber
问题描述: 意思就是说:给定一个数组,寻找一种选取方法,使得在保证任何两个相邻元素不同时被选的条件下得到的数值总和最大. 1. 递归 设nums为数组首地址,numsSize为数组的大小,max[i] ...
- leetcode每日刷题计划-简单篇day5
刷题成习惯以后感觉挺好的 Num 27 移除元素 Remove Element 跟那个排序去掉相同的一样,len标记然后新的不重复的直接放到len class Solution { public: i ...
- 【LeetCode算法题库】Day5:Roman to Integer & Longest Common Prefix & 3Sum
[Q13] Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Valu ...
- 我为什么要写LeetCode的博客?
# 增强学习成果 有一个研究成果,在学习中传授他人知识和讨论是最高效的做法,而看书则是最低效的做法(具体研究成果没找到地址).我写LeetCode博客主要目的是增强学习成果.当然,我也想出名,然而不知 ...
- LeetCode All in One 题目讲解汇总(持续更新中...)
终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...
- [LeetCode] Longest Substring with At Least K Repeating Characters 至少有K个重复字符的最长子字符串
Find the length of the longest substring T of a given string (consists of lowercase letters only) su ...
- Leetcode 笔记 113 - Path Sum II
题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...
- Leetcode 笔记 112 - Path Sum
题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...
- Leetcode 笔记 110 - Balanced Binary Tree
题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For ...
随机推荐
- ssh能够连接而sftp不能连接的解决方法
ssh能够连接而sftp不能连接的解决方法 昨天开始用FileZilla一直不能登录远程的服务器,ssh的登录就OK,因为是服务器,也不敢乱动.查了好多资料终于解决了. 首先,查看一下系统的安全日 ...
- MVC 创建Word文档
/// <summary> /// 创建一个word /// </summary> /// <returns></returns> public Act ...
- 移动端h5页面的设计稿尺寸
当我们在做手机端H5网页设计稿时(当然包含微信端的H5网页设计),如果没有做过类似的移动端的设计,UI设计师和前端工程师肯定会纠结的.如果是app设计师,就不会那么纠结啦. 延伸阅读: 2015年度最 ...
- 使用FusionCharts出柱状图和饼状图
在最近的项目中,需要使用出图,能够查看柱状图,饼状图等效果,刚开始我们用JS写的效果,发现效果不理想,找了一个JS插件发现效果还是不理想,客户也不满意,客户希望要很炫的效果,最后我们使用了Fusion ...
- DDMS工具使用(转)
DDMS工具使用 一.查看进程的堆栈使用情况1.选中你要查看的进程:2.点击“ Update Heap”按钮开启该进程的该项功能,如果单独打开ddms工具,按钮名为“Show heap updat ...
- ERROR security.UserGroupInformation
[java] 15/11/14 12:58:19 WARN mapred.JobClient: Use GenericOptionsParser for parsing the arguments. ...
- C# devExpress BandedGridView属性 备忘
BandedGridView属性备忘 StringBuilder sb = new StringBuilder(); DevExpress.XtraGrid.Views.BandedGrid.Band ...
- kindeditor集成ckplayer(带右键编辑菜单)
相信好多朋友为开源web编辑器没有集成视频播放器而烦恼,于是我就是试着修改了一下kindeditor,其实ueditor应该也是同样的,好了不多说了直接上图吧 kindeditor版本: 4.1.7 ...
- document.createElement方法的使用
我们在使用createElemen方法t创建一个元素节点的时候,似乎在IE下面怎么写都可以,但切换到FF等其它浏览器却总是会报错. 比如我们要创建一个input元素,那么在IE下,我们可以有多种写法: ...
- 定时且周期性的任务研究I--Timer
很多时候我们希望任务可以定时的周期性的执行,在最初的JAVA工具类库中,通过Timer可以实现定时的周期性的需求,但是有一定的缺陷,例如:Timer是基于绝对时间的而非支持相对时间,因此Timer对系 ...