转载请注明原文地址: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. ios之网络异常与正常视图的切换

    1. xib中创建两个View 2. View的视图大概如下第一个:View View 第二个:View 3. 代码切换: [self.view addSubview:_redView];  // 会 ...

  2. jquery入门 改动网页背景颜色

    我们在浏览一些站点,尤其是一些小说站点的时候,都会有改动页面背景颜色的地方,这个功能使用jquery非常easy实现. 效果图: show you code: <!doctype html> ...

  3. ArrayAdapter使用方法

    ArrayAdapter是一个简单的适配器,他的作用是将一个数组中的内容放入listView中.listView的item必须为textView. MainActivity.java package ...

  4. 基于JAVA原生HTTP请求工具类 httphelper

    原文地址;http://lushuifa.iteye.com/blog/2313896 import java.io.BufferedReader; import java.io.BufferedWr ...

  5. Servlet与JSP的区别(转)

    原文链接:Servlet与JSP的区别 两者之间的联系和区别 [1]JSP第一次运行的时候会编译成Servlet,驻留在内存中以供调用. [2]JSP是web开发技术,Servlet是服务器端运用的小 ...

  6. Shell bc命令进行数学运算

    通常情况做简单的运算,很多命令里面都是支持的.比如for, awk等. #!/bin/bash num= #for循环这里的数字也是运算 #也可以使用 #也可以使用数组 ;i<=;++i)) d ...

  7. Poly2Tri介绍[转]

    https://blog.csdn.net/xys206006/article/details/83002326 这是Poly2Tri介绍的翻译博文.原文链接:http://sites-final.u ...

  8. 用非递归、不用栈的方法,实现原位(in-place)的快速排序

    大体思路是修改Partition方法将原本枢数的调整放到方法结束后去做.这样因为数组右侧第一个大于当前枢数的位置就应该是未划分的子数组的边界.然后继续进行Partition调整.这种写法照比递归的写法 ...

  9. Impala 数值函数大全(转载)

    官网:https://www.cloudera.com/documentation/enterprise/latest/topics/impala_math_functions.html 转载链接1: ...

  10. rqnoj-329-刘翔!加油!-二维背包

    注意排除干扰项. 因为价值不会相等,所以价值的多少与本题没有任何关系,. 所以价值为干扰项,所以不用考虑. 二维背包,简单求解. #include<stdio.h> #include< ...