【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的更多相关文章

  1. LeetCode Day5——House Robber

    问题描述: 意思就是说:给定一个数组,寻找一种选取方法,使得在保证任何两个相邻元素不同时被选的条件下得到的数值总和最大. 1. 递归 设nums为数组首地址,numsSize为数组的大小,max[i] ...

  2. leetcode每日刷题计划-简单篇day5

    刷题成习惯以后感觉挺好的 Num 27 移除元素 Remove Element 跟那个排序去掉相同的一样,len标记然后新的不重复的直接放到len class Solution { public: i ...

  3. 【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 ...

  4. 我为什么要写LeetCode的博客?

    # 增强学习成果 有一个研究成果,在学习中传授他人知识和讨论是最高效的做法,而看书则是最低效的做法(具体研究成果没找到地址).我写LeetCode博客主要目的是增强学习成果.当然,我也想出名,然而不知 ...

  5. LeetCode All in One 题目讲解汇总(持续更新中...)

    终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...

  6. [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 ...

  7. 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 ...

  8. Leetcode 笔记 112 - Path Sum

    题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...

  9. Leetcode 笔记 110 - Balanced Binary Tree

    题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For ...

随机推荐

  1. 解决Android Studio Gradle Build特别慢的问题

    解决Android Studio Gradle Build 特别慢的问题 C:\Users\你的用户名\.gradle目录下新建一个文件名为gradle.properties的文件.内容为:org.g ...

  2. netty最快?

    http://www.techempower.com/blog/2013/04/05/frameworks-round-2/

  3. memcache command

    http://www.cnblogs.com/jeffwongishandsome/archive/2011/11/06/2238265.html

  4. 智力大冲浪(riddle)

    智力大冲浪(riddle) 题目描述 小伟报名参加中央电视台的智力大冲浪节目.本次挑战赛吸引了众多参赛者,主持人为了表彰大家的勇气,先奖励每个参赛者m元.先不要太高兴!因为这些钱还不一定都是你的?!接 ...

  5. Quartz 2D 初步

    转载自:http://www.cofcool.net/development/2015/06/17/ios-study-note-six-Quartz2D/ Quartz 2D是一个二维绘图引擎,同时 ...

  6. RunTime 入门

    原文链接:http://www.jianshu.com/p/59992507f875 这是一篇浅显实用 易记 易理解的关于runtime的解读. Runtime 中的方法主要以五个单词开头——clas ...

  7. mr本地运行的几种模式

    MR程序的几种提交运行模式 本地模型运行 1/在windows的eclipse里面直接运行main方法,就会将job提交给本地执行器localjobrunner执行 ----输入输出数据可以放在本地路 ...

  8. HTML5 学习01

    HTML的英语意思是:Hypertext Marked Language,即超文本标记语言,是一种用来制作超文本文档的简单标记语言. 所谓超文本,是因为它可以加入图片.声音.动画.影视等内容,事实上每 ...

  9. 转:sql SELECT时的with(nolock)选项说明

    I used to see my senior developers use WITH (NOLOCK) when querying in SQL Server and wonder why they ...

  10. MVC3在页面上获取当前控制器名称、Action名称以及路由参数

    获取控制器名称: ViewContext.RouteData.Values["controller"].ToString(); 获取Action名称: ViewContext.Ro ...