转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6409067.html

1:Hamming distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

此题求汉明距离。学过计网都让应该都知道了,汉明距离就是两个二进制串异或的结果的1的个数。按此原理,我们可以直接求出x^y结果,然后遍历结果中1的个数。

而一个整数怎么遍历它的二进制串呢?用位运算中的右移,每次右移一位,和1取&即可。

public int hammingDistance(int x, int y) {
int res=0,xor=x^y;
for (int i = 0; i < 32; i++) {
res+=(xor&1);
xor=(xor>>1);
}
return res;
}

2:Number Complement

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

此题为求一个数的二进制表示除去前导零后部分按位取反。注意这里不是简单的求一个数的按位取反,因为这里是不算前导零部分的。简单的“~X”的结果是“-(X+1)”,而这里不是。

解题思路是:把这个数从低位到高位遍历,每次右移1位&1得出当前位的数值,并且用index记录当前位下标。然后当前位置数值与1异或即实现“1变0,0变1”。最后,把01互换后的数值左移回index位即得当前位乘以权重是多少,加到res中。直到除去前导零的部分全部遍历完,res即为所求结果。这里判断遍历完的思路是:tempnum=0。因为每遍历一位右移1,所以遍历完后剩下前导零,当前数值为0.

public int findComplement(int num) {
int index=0;
int res=0;
int tempnum=num;
int curr;
while(tempnum>0){
curr=(tempnum&1)^1;
res+=(curr<<index);
tempnum=tempnum>>1;
++index;
}
return res;
}

3:Keyboard Row

Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.

此题为:输入一个字符串数组,要求输出这个数组中能够在美式键盘同一行打出的元素。比如  dad  的字符都在键盘同一行,hello不是。所以dad满足要求。

思路:我的思路是,键盘三行,一行保存为一个字符串。然后对于输入的字符串数组进行遍历。对于当前元素的第一个字母,在键盘三个字符串中indexOf(ch)得出第一个字母在哪一行。然后,就在这一行字符串逐个indexOf()剩下的字母,如果有一个找不到,则说明跨行了。否则,把这个元素添加到list中。直到输入的字符串数组所有元素遍历完,把list转换为String[]返回即可。

 public String[] findWords(String[] words) {
String[] lines={"QWERTYUIOP","ASDFGHJKL","ZXCVBNM"};
List<String> res=new ArrayList<String>();
for(String word:words){
char[] chars=word.toUpperCase().toCharArray();
int lineindex=-1;
boolean flag=true;
for(int i=0;i<3;++i){
if(lines[i].indexOf(chars[0])>=0){
lineindex=i;
break;
}
}
for(int i=1;i<chars.length;++i){
if(lines[lineindex].indexOf(chars[i])<0){
flag=false;
break;
}
}
if(flag){
res.add(word);
}
}
//这里注意List转换为String数组是通过 list.toArray(new String[0])实现的
return res.toArray(new String[0]);
}

有一种做法更优化,使用了HashMap,把每一行字符保存到一个map中,同一行的拥有同一value值。然后同样,也是遍历输入的字符串数组的元素的每一个字母,获取他们的行值。有一个行值与前面不同就说明跨行。

public class Solution {
public String[] findWords(String[] words) {
String[] strs = {"QWERTYUIOP","ASDFGHJKL","ZXCVBNM"};
Map<Character, Integer> map = new HashMap<>();
for(int i = 0; i<strs.length; i++){
for(char c: strs[i].toCharArray()){
map.put(c, i);
}
}
List<String> res = new LinkedList<>();
for(String w: words){
if(w.equals("")) continue;
int index = map.get(w.toUpperCase().charAt(0));
for(char c: w.toUpperCase().toCharArray()){
if(map.get(c)!=index){
index = -1;
break;
}
}
if(index!=-1) res.add(w);
}
return res.toArray(new String[0]);
}
}

4:Next Greater Element I

You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.

The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

此题:给出两个数组nums1和nums2,nums1为nums2的子集。然后对于nums1中每个元素,找出其在nums2中紧随其后的第一个大于它的数值。有则返回该数值,无则返回-1。

思路:用嵌套循环,外层循环遍历nums1,内层循环遍历nums2,满足条件  nums2[i]>j并且i>j的下标即得nums2中大于j并且下标大于j的数,而在第一次获得该数时就break即可得到紧随其后的第一个大于j的值。

public int[] nextGreaterElement(int[] findNums, int[] nums) {
List res=new ArrayList();
for(int j:findNums){
int greater=-1;
int jindex=nums.length;
for(int i=0;i<nums.length;++i){
if(nums[i]==j){jindex=i;}
if((nums[i]>j)&&(i>jindex)){
greater=nums[i];
break;
}
}
res.add(greater);
}
int[] result=new int[res.size()];
for(int i=0;i<res.size();++i){
result[i]=(Integer) res.get(i);
}
return result;
}

上面做法浪费的地方在于,每次内层循环需要从nums2的0左边开始遍历,浪费时间。如果可以每次直接从nums2中的nums1元素值处开始遍历,直接找第一个大于它的值,就会快很多。这种把值与下标记录下来以免每次都需要遍历一次找下标的优化方法就是——使用map。

public int[] nextGreaterElement(int[] findNums, int[] nums) {
int[] result=new int[findNums.length];
//首先,用一个map把nums的数值与下标记录下来
Map<Integer,Integer> map=new HashMap();
for(int i=0;i<nums.length;++i){
map.put(nums[i], i);
}
for(int i=0;i<findNums.length;++i){
//在遍历findnums的元素时,直接通过map.get(key)找到nums中相应元素的下标作为遍历nums的起始位置
int startindex=map.get(findNums[i]);
for(int j=startindex;j<nums.length;++j){
if(nums[j]>findNums[i]){
result[i]=nums[j];
break;
}
result[i]=-1;
}
}
return result;
}

还有一种做法相当于记忆化搜索。先由nums2,用一个map把num2每一个元素的与紧随其后的第一个大于它的值建立起映射。无则不管。然后,在遍历nums1时,直接由这个map去get(key)获取第一个大于它的数值即可。有则返回数值,无则返回空,则我们返回-1。

public int[] nextGreaterElement(int[] findNums, int[] nums) {
int[] result=new int[findNums.length];
Stack<Integer> stack=new Stack<Integer>();
Map<Integer,Integer> map=new HashMap<Integer, Integer>();
//逐个把nums入栈,并且从第二个起,逐个与栈顶元素比较,大于它则说明此数为第一个大于栈顶元素的值,记录到map去,并把栈顶弹出。否,则把这个元素入栈。遍历下一个
for(int num:nums){
//对当前nums元素,用一个while处理栈中待处理的元素们:栈顶<当前元素,则记录到map并弹出。此时若栈未空,且栈顶继续<当前nums元素,则继续记录到map
while(!stack.empty() && stack.peek()<num){
map.put(stack.pop(), num);
}
//把当前元素入栈,在之后的循环中寻找大于它的元素
stack.push(num);
}
for(int i=0;i<findNums.length;++i){
result[i] = map.get(findNums[i])==null?-1:map.get(findNums[i]);
}
return result;
}

5:Fizz Buzz

Write a program that outputs the string representation of numbers from 1 to n.But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

此题:写一个程序打印1到100这些数字。但是遇到数字为3的倍数的时候,打印“Fizz”替代数字,5的倍数用“Buzz”代替,既是3的倍数又是5的倍数打印“FizzBuzz”。

思路:此题,若用暴力法的话就太不明智了。因为n大小没定,如果从1到n逐个遍历都对3、5取余的话耗时太多太多了。我的做法是,借助上一题的灵感:首先由n求出1~nz之间3、5的倍数们,并用两个map记录下来。然后在遍历1~n时,只需分别从map3/map5去get(i),有的对象返回则说明i为 3/5的倍数,分4种组合情况,用if-else if语句分别处理即可。

 public List<String> fizzBuzz(int n) {
List<String> resList=new ArrayList<String>();
//求出n之内3、5的最大倍数
int times_of_three=(int) Math.floor(n/3);
int times_of_five=(int) Math.floor(n/5);
//把1~n的3、5倍数值放到map里
Map<Integer, Integer> map3=new HashMap<Integer, Integer>();
Map<Integer, Integer> map5=new HashMap<Integer, Integer>();
for(int i=1;i<=times_of_three;++i){
map3.put(3*i, i);
}
for(int i=1;i<=times_of_five;++i){
map5.put(5*i, i);
}
//遍历1~n。对每个i分4种情况处理
for(int i=1;i<=n;++i){
if(map3.get(i)!=null && map5.get(i)!=null){
resList.add("FizzBuzz");
}else if (map3.get(i)!=null && map5.get(i)==null) {
resList.add("Fizz");
}else if (map3.get(i)==null && map5.get(i)!=null) {
resList.add("Buzz");
}else{
resList.add(""+i);
}
}
return resList;
}

还有一种方法,是用步长取代求余。思路可借鉴博客:http://blog.csdn.net/ixidof/article/details/7697173

【leetcode】solution in java——Easy1的更多相关文章

  1. 【leetcode】solution in java——Easy4

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6415011.html 16:Invert Binary Tree 此题:以根为对称轴,反转二叉树. 思路:看到 ...

  2. 【leetcode】solution in java——Easy3

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6412505.html 心得:看到一道题,优先往栈,队列,map,list这些工具的使用上面想.不要来去都是暴搜 ...

  3. 【leetcode】solution in java——Easy2

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6410409.html 6:Reverse String Write a function that takes ...

  4. 【leetcode】solution in java——Easy5

    转载请注明原文地址: 21:Assign Cookies Assume you are an awesome parent and want to give your children some co ...

  5. 【Leetcode】Reorder List JAVA

    一.题目描述 Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You must ...

  6. 【Leetcode】Sort List JAVA实现

    Sort a linked list in O(n log n) time using constant space complexity. 1.分析 该题主要考查了链接上的合并排序算法. 2.正确代 ...

  7. 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java

    [LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum dept ...

  8. 【刷题】【LeetCode】007-整数反转-easy

    [刷题][LeetCode]总 用动画的形式呈现解LeetCode题目的思路 参考链接-空 007-整数反转 方法: 弹出和推入数字 & 溢出前进行检查 思路: 我们可以一次构建反转整数的一位 ...

  9. 【LeetCode】Permutations 解题报告

    全排列问题.经常使用的排列生成算法有序数法.字典序法.换位法(Johnson(Johnson-Trotter).轮转法以及Shift cursor cursor* (Gao & Wang)法. ...

随机推荐

  1. 我们的生活第二季/全集This Is Us迅雷下载

    NBC剧集<我们这一天>宣布一次性续订2.3季,这部Dan Fogelman打造的大热剧是这个秋季档收视人数第二的广播网剧情剧.新续订的两季还是每季18集. NBC的叫好叫座剧<我们 ...

  2. 再有人问你volatile是什么,把这篇文章也发给他

    在上一篇文章中,我们围绕volatile关键字做了很多阐述,主要介绍了volatile的用法.原理以及特性.在上一篇文章中,我提到过:volatile只能保证可见性和有序性,无法保证原子性.关于这部分 ...

  3. [转]一次非常有意思的sql优化经历

    From :http://www.cnblogs.com/tangyanbo/p/4462734.html 补充:看到这么多朋友对sql优化感兴趣,我又重新补充了下文章的内容,将更多关于sql优化的知 ...

  4. mysqldump参数详细说明

    Mysqldump参数大全(参数来源于mysql5.5.19源码)   参数 参数说明 --all-databases  , -A 导出全部数据库. mysqldump  -uroot -p --al ...

  5. mysql权限管理命令示例

    mysql权限管理命令示例 grant all privileges on *.* to *.* identified by 'hwalk1'; flush privileges; insert in ...

  6. jQuery中attr()和prop()的区别,修改checked属性 jquery attr('checked' 不起作用 attr('checked' 不对

    在做复选框全选按钮的时候,出现了一个问题,使用语句$.attr('checked',true),将复选框的属性改为被选中,在chrome浏览器中第一次点击有效后面就不行了,IE8倒是没有问题. 百度了 ...

  7. eclipse 创建聚合maven项目

    本人不想花太多时间去排版,所以这里排版假设不好看,请多多包涵! 一直都在用maven,可是却基本没有自己创建过maven项目,今天也试着创建一个. 1.打开eclipse.然后new,other,然后 ...

  8. Tomcat6和Tomcat7配置SSL通信的比较

    <Tomcat6和Tomcat7配置SSL通信的比较> 作者:chszs,转载需注明.博客主页: http://blog.csdn.net/chszs 在项目开发过程中,尝尝会遇到Tomc ...

  9. 为sharepoint的内部页面添加后台代码

    我们知道,存储在数据库里的SharePoint页面是不能直接添加后台代码的,这给我们带来了很多的不方便,比如想要在页面上实现一些东西,都必 须使用Webpart或者自定义控件的方式,哪怕仅仅是很简单的 ...

  10. libnids

    一.简介 libnids的英文意思是 Network Intrusion Detect System library,即网络入侵监测系统函数库.它是在前面介绍的两种C函数接口库libnet和libpc ...