【leetcode】solution in java——Easy1

转载请注明原文地址: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

原文地址:https://www.cnblogs.com/ygj0930/p/6409067.html