【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. Ubuntu下安装使用MongoDB

    安装 官网下载: https://www.mongodb.org/ 解压解包 重命名为mongodb 移动到/usr/local/目录下 创建连个软连接  ln -s /usr/local/mongo ...

  2. Spring的事务传播机制

    1.事务传播类型     新建事务 required required_new   - 挂起当前    非事务方式运行 supports not_supported  - 挂起当前 never    ...

  3. robot_framewok自动化测试

    robot_framewok自动化测试 http://wenku.baidu.com/view/691abcaa4b73f242336c5fec.html 接口自动化测试框架设计 http://wen ...

  4. Bootstrap 模态对话框只加载一次 remote 数据的解决办法 转载

    http://my.oschina.net/qczhang/blog/190215 摘要 前端框架 Bootstrap 的模态对话框,可以使用 remote 选项指定一个 URL,这样对话框在第一次弹 ...

  5. 将json转化为model

    /// <summary> /// 获取Json的Model /// </summary> /// <typeparam name="T">&l ...

  6. Linux 查看 硬件配置

    一:查看cpu more /proc/cpuinfo | grep "model name" grep "model name" /proc/cpuinfo 如 ...

  7. javascript 中 apply(或call)方法的用途----对象的继承

    一直以来,我的理解就是  js中的Function.apply(或者是Function.call)方法是来改变Function 这个函数的执行上下文(excute Context),说白了,就是改变执 ...

  8. CentOS下自动登陆root帐户

    1 vi /etc/pam.d/gdm 把 auth required …… root quiet这行注释掉 2 vi /etc/pam.d/gdm-passwd 同上 3 vi /etc/gdm/c ...

  9. CentOS 在同一窗口打开文件夹

    1.打开一个文件夹 2.编辑 - 首选项 - 行为,勾选“总是在浏览器窗口打开”,点击关闭.

  10. 手把手教你使用startuml画用例图

    转自:http://www.2cto.com/os/201502/377091.html 最近准备研究下volley的源码,但看了网上一些大牛的博客都是配合图这样看起来更直观,分析起来逻辑也很好,什么 ...