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 ...
随机推荐
- HDU 2475 BOX 动态树 Link-Cut Tree
Box Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) [Problem De ...
- Genymotion开启就全部白屏解决方法
Genymotion开启就整个界面全部白屏,包括菜单栏也白屏,解决方法: 很可能是显卡驱动有问题,用驱动人生或者驱动精灵更新显卡驱动就可以了. 目前开发者好用的模拟器有: 1.Genymotion 2 ...
- EXCEL读写NPOI
1.第一步: 可以使用ExcelAutomation进行EXCEl文件的读写,但是需要电脑上安装EXCEL,对EXCEL版本有要求,速度慢,有安全性,并发性问题,不适合网站类项目. 第二种方法: NP ...
- islands打炉石传说<DP>
islands最近在完一款游戏"炉石传说",又名"魔兽英雄传".炉石传说是一款卡牌类对战的游戏.游戏是2人对战,总的来说,里面的卡牌分成2类,一类是法术牌,另一 ...
- android 修改listview item view 的方法(转)
android 修改listview item view 的方法 具体的解答办法很简单: 代码如下 : 1.获取需要更新的view int visiblePosition = mListView. ...
- margin问题
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- led.c驱动框架2nd
led.c: #include <linux/module.h> #include <linux/init.h> #include <linux/fs.h> ; v ...
- sql server 日期转换函数 convert()
--内容来自:http://hi.baidu.com/muqingz/item/8fb7b3ca8a485b0cac092f7b Select CONVERT(varchar(100), GETDAT ...
- WebDriver(Selenium2) 处理可能存在的JS弹出框
http://uniquepig.iteye.com/blog/1703103 在自动化测试过程中,有些情况下我们会遇到一些潜在的Javascript弹出框.(即某些条件下才会出现,不是固定出现),然 ...
- mysql优化---第7篇:参数 innodb_buffer_pool_instances设置
摘要:1 innodb_buffer_pool_instances可以开启多个内存缓冲池,把需要缓冲的数据hash到不同的缓冲池中,这样可以并行的内存读写. 2 innodb_buffer_pool_ ...