算法和编程面试题

1. 判断身份证:要么是15位,要么是18位,最后一位可以为字母,并写程序提出其中的年月日。

我们可以用正则表达式来定义复杂的字符串格式,

(\d{17}[0-9a-zA-Z]|\d{14}[0-9a-zA-Z])可以用来判断是否为合法的15位或18位身份证号码。

因为15位和18位的身份证号码都是从7位到第12位为身份证为日期类型。这样我们可以设计出更精确的正则模式,使身份证号的日期合法,这样我们的正则模式可以进一步将日期部分的正则修改为[12][0-9]{3}[01][0-9][123][0-9],当然可以更精确的设置日期。

在jdk的java.util.Regex包中有实现正则的类,Pattern和Matcher。以下是实现代码:

  1. importjava.util.regex.Matcher;  
  2.   
  3. importjava.util.regex.Pattern;  
  4.   
  5. public classRegexTest {  
  6.   
  7.          public static void main(String[] args){  
  8.   
  9.                    // 测试是否为合法的身份证号码   
  10.   
  11.                    String[] strs = {"130681198712092019""13068119871209201x",  
  12.   
  13.                                      "13068119871209201","123456789012345""12345678901234x",  
  14.   
  15.                                      "1234567890123"};  
  16.   
  17.                    Pattern p1 =Pattern.compile("(\\d{17}[0-9a-zA-Z]|\\d{14}[0-9a-zA-Z])");  
  18.   
  19.                    for (int i = 0; i <strs.length; i++) {  
  20.   
  21.                             Matcher matcher =p1.matcher(strs[i]);  
  22.   
  23.                             System.out.println(strs[i]+ ":" + matcher.matches());  
  24.   
  25.                    }  
  26.   
  27.    
  28.   
  29.                    Pattern p2 =Pattern.compile("\\d{6}(\\d{8}).*"); // 用于提取出生日字符串   
  30.   
  31.                    Pattern p3 =Pattern.compile("(\\d{4})(\\d{2})(\\d{2})");// 用于将生日字符串进行分解为年月日   
  32.   
  33.                    for (int i = 0; i <strs.length; i++) {  
  34.   
  35.                             Matcher matcher =p2.matcher(strs[i]);  
  36.   
  37.                             boolean b =matcher.find();  
  38.   
  39.                             if (b) {  
  40.   
  41.                                      String s =matcher.group(1);  
  42.   
  43.                                      Matchermatcher2 = p3.matcher(s);  
  44.   
  45.                                      if(matcher2.find()) {  
  46.   
  47.                                                System.out  
  48.   
  49.                                                                  .println("生日为" + matcher2.group(1) + "年"  
  50.   
  51.                                                                                     +matcher2.group(2) + "月"  
  52.   
  53.                                                                                     +matcher2.group(3) + "日");  
  54.   
  55.                                      }}}}}  
importjava.util.regex.Matcher;

importjava.util.regex.Pattern;

public classRegexTest {

         public static void main(String[] args){

                   // 测试是否为合法的身份证号码

                   String[] strs = {"130681198712092019", "13068119871209201x",

                                     "13068119871209201","123456789012345", "12345678901234x",

                                     "1234567890123"};

                   Pattern p1 =Pattern.compile("(\\d{17}[0-9a-zA-Z]|\\d{14}[0-9a-zA-Z])");

                   for (int i = 0; i <strs.length; i++) {

                            Matcher matcher =p1.matcher(strs[i]);

                            System.out.println(strs[i]+ ":" + matcher.matches());

                   }

 

                   Pattern p2 =Pattern.compile("\\d{6}(\\d{8}).*"); // 用于提取出生日字符串

                   Pattern p3 =Pattern.compile("(\\d{4})(\\d{2})(\\d{2})");// 用于将生日字符串进行分解为年月日

                   for (int i = 0; i <strs.length; i++) {

                            Matcher matcher =p2.matcher(strs[i]);

                            boolean b =matcher.find();

                            if (b) {

                                     String s =matcher.group(1);

                                     Matchermatcher2 = p3.matcher(s);

                                     if(matcher2.find()) {

                                               System.out

                                                                 .println("生日为" + matcher2.group(1) + "年"

                                                                                    +matcher2.group(2) + "月"

                                                                                    +matcher2.group(3) + "日");

                                     }}}}}


 

 

2编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔。

答:

             

  1. package cn.itcast;  
  2.   
  3.    
  4.   
  5. import java.io.File;  
  6.   
  7. import java.io.FileReader;  
  8.   
  9. import java.io.FileWriter;  
  10.   
  11.    
  12.   
  13. public class MainClass{  
  14.   
  15.        public static voidmain(String[] args) throws Exception{  
  16.   
  17.               FileManager a = newFileManager("a.txt",new char[]{'\n'});  
  18.   
  19.               FileManager b = newFileManager("b.txt",new char[]{'\n',' '});             
  20.   
  21.               FileWriter c = newFileWriter("c.txt");  
  22.   
  23.               String aWord = null;  
  24.   
  25.               String bWord = null;  
  26.   
  27.               while((aWord =a.nextWord()) !=null ){  
  28.   
  29.                      c.write(aWord+ "\n");  
  30.   
  31.                      bWord =b.nextWord();  
  32.   
  33.                      if(bWord !=null)  
  34.   
  35.                             c.write(bWord+ "\n");  
  36.   
  37.               }  
  38.   
  39.                 
  40.   
  41.               while((bWord =b.nextWord()) != null){  
  42.   
  43.                      c.write(bWord+ "\n");  
  44.   
  45.               }        
  46.   
  47.               c.close();  
  48.   
  49.        }  
  50.   
  51.          
  52.   
  53. }  
  54.   
  55.    
  56.   
  57.    
  58.   
  59. class FileManager{  
  60.   
  61.    
  62.   
  63.        String[] words = null;  
  64.   
  65.        int pos = 0;  
  66.   
  67.        public FileManager(Stringfilename,char[] seperators) throws Exception{  
  68.   
  69.               File f = newFile(filename);  
  70.   
  71.               FileReader reader =new FileReader(f);  
  72.   
  73.               char[] buf = newchar[(int)f.length()];  
  74.   
  75.               int len =reader.read(buf);  
  76.   
  77.               String results = newString(buf,0,len);  
  78.   
  79.               String regex = null;  
  80.   
  81.               if(seperators.length>1 ){  
  82.   
  83.                      regex ="" + seperators[0] + "|" + seperators[1];  
  84.   
  85.               }else{  
  86.   
  87.                      regex ="" + seperators[0];  
  88.   
  89.               }  
  90.   
  91.               words =results.split(regex);  
  92.   
  93.        }  
  94.   
  95.          
  96.   
  97.        public String nextWord(){  
  98.   
  99.               if(pos ==words.length)  
  100.   
  101.                      return null;  
  102.   
  103.               return words[pos++];  
  104.   
  105.        }  
  106.   
  107.    
  108.   
  109. }  
package cn.itcast;

 

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

 

public class MainClass{

       public static voidmain(String[] args) throws Exception{

              FileManager a = newFileManager("a.txt",new char[]{'\n'});

              FileManager b = newFileManager("b.txt",new char[]{'\n',' '});           

              FileWriter c = newFileWriter("c.txt");

              String aWord = null;

              String bWord = null;

              while((aWord =a.nextWord()) !=null ){

                     c.write(aWord+ "\n");

                     bWord =b.nextWord();

                     if(bWord !=null)

                            c.write(bWord+ "\n");

              }

              

              while((bWord =b.nextWord()) != null){

                     c.write(bWord+ "\n");

              }      

              c.close();

       }

       

}

 

 

class FileManager{

 

       String[] words = null;

       int pos = 0;

       public FileManager(Stringfilename,char[] seperators) throws Exception{

              File f = newFile(filename);

              FileReader reader =new FileReader(f);

              char[] buf = newchar[(int)f.length()];

              int len =reader.read(buf);

              String results = newString(buf,0,len);

              String regex = null;

              if(seperators.length>1 ){

                     regex ="" + seperators[0] + "|" + seperators[1];

              }else{

                     regex ="" + seperators[0];

              }

              words =results.split(regex);

       }

       

       public String nextWord(){

              if(pos ==words.length)

                     return null;

              return words[pos++];

       }

 

}


 

3、编写一个程序,将d:\java目录下的所有.java文件复制到d:\jad目录下,并将原来文件的扩展名从.java改为.jad。

(大家正在做上面这道题,网上迟到的朋友也请做做这道题,找工作必须能编写这些简单问题的代码!)

答:listFiles方法接受一个FileFilter对象,这个FileFilter对象就是过虑的策略对象,不同的人提供不同的FileFilter实现,即提供了不同的过滤策略。

  1. import java.io.File;  
  2.   
  3. import java.io.FileInputStream;  
  4.   
  5. import java.io.FileOutputStream;  
  6.   
  7. import java.io.FilenameFilter;  
  8.   
  9. import java.io.IOException;  
  10.   
  11. import java.io.InputStream;  
  12.   
  13. import java.io.OutputStream;  
  14.   
  15.    
  16.   
  17. public class Jad2Java {  
  18.   
  19.    
  20.   
  21.        public static voidmain(String[] args) throws Exception {  
  22.   
  23.               File srcDir = new File("java");  
  24.   
  25.               if(!(srcDir.exists()&& srcDir.isDirectory()))  
  26.   
  27.                             thrownew Exception("目录不存在");  
  28.   
  29.               File[] files =srcDir.listFiles(  
  30.   
  31.                      newFilenameFilter(){  
  32.   
  33.    
  34.   
  35.                                    publicboolean accept(File dir, String name) {  
  36.   
  37.                                           returnname.endsWith(".java");  
  38.   
  39.                                    }  
  40.   
  41.                                      
  42.   
  43.                             }  
  44.   
  45.               );  
  46.   
  47.                 
  48.   
  49.               System.out.println(files.length);  
  50.   
  51.               File destDir = newFile("jad");  
  52.   
  53.               if(!destDir.exists())destDir.mkdir();  
  54.   
  55.               for(File f :files){  
  56.   
  57.                      FileInputStream  fis = new FileInputStream(f);  
  58.   
  59.                      StringdestFileName = f.getName().replaceAll("\\.java{1}quot;, ".jad");  
  60.   
  61.                      FileOutputStreamfos = new FileOutputStream(new File(destDir,destFileName));  
  62.   
  63.                      copy(fis,fos);  
  64.   
  65.                      fis.close();  
  66.   
  67.                      fos.close();  
  68.   
  69.               }  
  70.   
  71.        }  
  72.   
  73.          
  74.   
  75.        private static voidcopy(InputStream ips,OutputStream ops) throws Exception{  
  76.   
  77.               int len = 0;  
  78.   
  79.               byte[] buf = newbyte[1024];  
  80.   
  81.               while((len =ips.read(buf)) != -1){  
  82.   
  83.                      ops.write(buf,0,len);  
  84.   
  85.               }  
  86.   
  87.    
  88.   
  89.        }  
  90.   
  91. }  
import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.FilenameFilter;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

 

public class Jad2Java {

 

       public static voidmain(String[] args) throws Exception {

              File srcDir = new File("java");

              if(!(srcDir.exists()&& srcDir.isDirectory()))

                            thrownew Exception("目录不存在");

              File[] files =srcDir.listFiles(

                     newFilenameFilter(){

 

                                   publicboolean accept(File dir, String name) {

                                          returnname.endsWith(".java");

                                   }

                                   

                            }

              );

              

              System.out.println(files.length);

              File destDir = newFile("jad");

              if(!destDir.exists())destDir.mkdir();

              for(File f :files){

                     FileInputStream  fis = new FileInputStream(f);

                     StringdestFileName = f.getName().replaceAll("\\.java{1}quot;, ".jad");

                     FileOutputStreamfos = new FileOutputStream(new File(destDir,destFileName));

                     copy(fis,fos);

                     fis.close();

                     fos.close();

              }

       }

       

       private static voidcopy(InputStream ips,OutputStream ops) throws Exception{

              int len = 0;

              byte[] buf = newbyte[1024];

              while((len =ips.read(buf)) != -1){

                     ops.write(buf,0,len);

              }

 

       }

}


 

由本题总结的思想及策略模式的解析:

1.

class jad2java{

       1. 得到某个目录下的所有的java文件集合

              1.1 得到目录 File srcDir =new File("d:\\java");

              1.2 得到目录下的所有java文件:File[] files =srcDir.listFiles(new MyFileFilter());

              1.3 只想得到.java的文件: classMyFileFilter implememyts FileFilter{

                     publicboolean accept(File pathname){

                            returnpathname.getName().endsWith(".java")

                     }

              }

             

       2.将每个文件复制到另外一个目录,并改扩展名

              2.1 得到目标目录,如果目标目录不存在,则创建之

              2.2 根据源文件名得到目标文件名,注意要用正则表达式,注意.的转义。

              2.3 根据表示目录的File和目标文件名的字符串,得到表示目标文件的File。

                     //要在硬盘中准确地创建出一个文件,需要知道文件名和文件的目录。

              2.4 将源文件的流拷贝成目标文件流,拷贝方法独立成为一个方法,方法的参数采用抽象流的形式。

                     //方法接受的参数类型尽量面向父类,越抽象越好,这样适应面更宽广。     

}

分析listFiles方法内部的策略模式实现原理

File[] listFiles(FileFilter filter){

       File[] files = listFiles();

       //ArraylistacceptedFilesList = new ArrayList();

       File[] acceptedFiles = newFile[files.length];

       int pos = 0;

       for(File file: files){

              boolean accepted =filter.accept(file);

              if(accepted){

                     //acceptedFilesList.add(file);

                     acceptedFiles[pos++]= file;

              }            

       }

      

       Arrays.copyOf(acceptedFiles,pos);

       //return(File[])accpetedFilesList.toArray();

      

}

3、编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串,但要保证汉字不被截取半个,如“我ABC”,4,应该截取“我AB”,输入“我ABC汉DEF”,6,应该输出“我ABC”,而不是“我ABC+汉的半个”。

答:

       首先要了解中文字符有多种编码及各种编码的特征。

    假设n为要截取的字节数。

      

  1. public static voidmain(String[] args) throws Exception{  
  2.   
  3.               String str = "我a爱中华abc我爱传智def';  
  4.   
  5.               String str = "我ABC汉";  
  6.   
  7.               int num =trimGBK(str.getBytes("GBK"),5);  
  8.   
  9.               System.out.println(str.substring(0,num));  
  10.   
  11.        }  
  12.   
  13.          
  14.   
  15.        public static int  trimGBK(byte[] buf,int n){  
  16.   
  17.               int num = 0;  
  18.   
  19.               booleanbChineseFirstHalf = false;  
  20.   
  21.               for(inti=0;i<n;i++)  
  22.   
  23.               {  
  24.   
  25.                      if(buf[i]<0&& !bChineseFirstHalf){  
  26.   
  27.                             bChineseFirstHalf= true;  
  28.   
  29.                      }else{  
  30.   
  31.                             num++;  
  32.   
  33.                             bChineseFirstHalf= false;                        
  34.   
  35.                      }  
  36.   
  37.               }  
  38.   
  39.               return num;  
  40.   
  41.        }  
public static voidmain(String[] args) throws Exception{

              String str = "我a爱中华abc我爱传智def';

              String str = "我ABC汉";

              int num =trimGBK(str.getBytes("GBK"),5);

              System.out.println(str.substring(0,num));

       }

       

       public static int  trimGBK(byte[] buf,int n){

              int num = 0;

              booleanbChineseFirstHalf = false;

              for(inti=0;i<n;i++)

              {

                     if(buf[i]<0&& !bChineseFirstHalf){

                            bChineseFirstHalf= true;

                     }else{

                            num++;

                            bChineseFirstHalf= false;                      

                     }

              }

              return num;

       }


 

1、有一个字符串,其中包含中文字符、英文字符和数字字符,请统计和打印出各个字符的个数。

答:哈哈,其实包含中文字符、英文字符、数字字符原来是出题者放的烟雾弹。

  1. String content = “中国aadf的111萨bbb菲的zz萨菲”;  
  2.   
  3. HashMap map = new HashMap();  
  4.   
  5. for(int i=0;i<content.length;i++)  
  6.   
  7. {  
  8.   
  9.        char c = content.charAt(i);  
  10.   
  11.        Integer num = map.get(c);  
  12.   
  13.        if(num == null)  
  14.   
  15.               num = 1;  
  16.   
  17.        else  
  18.   
  19.               num = num + 1;  
  20.   
  21.        map.put(c,num);  
  22.   
  23. }   
  24.   
  25. for(Map.EntrySet entry : map)  
  26.   
  27. {  
  28.   
  29.        system.out.println(entry.getkey()+ “:” + entry.getValue());  
  30.   
  31. }  
String content = “中国aadf的111萨bbb菲的zz萨菲”;

HashMap map = new HashMap();

for(int i=0;i<content.length;i++)

{

       char c = content.charAt(i);

       Integer num = map.get(c);

       if(num == null)

              num = 1;

       else

              num = num + 1;

       map.put(c,num);

} 

for(Map.EntrySet entry : map)

{

       system.out.println(entry.getkey()+ “:” + entry.getValue());

}


 

估计是当初面试的那个学员表述不清楚,问题很可能是:

如果一串字符如"aaaabbc中国1512"要分别统计英文字符的数量,中文字符的数量,和数字字符的数量,假设字符中没有中文字符、英文字符、数字字符之外的其他特殊字符。

 

1、说明生活中遇到的二叉树,用java实现二叉树

  1. int engishCount;  
  2.   
  3. int chineseCount;  
  4.   
  5. int digitCount;  
  6.   
  7. for(int i=0;i<str.length;i++)  
  8.   
  9. {  
  10.   
  11.     charch = str.charAt(i);  
  12.   
  13.     if(ch>=’0’ && ch<=’9’)  
  14.   
  15.     {  
  16.   
  17.        digitCount++  
  18.   
  19.     }  
  20.   
  21.     elseif((ch>=’a’&& ch<=’z’) ||(ch>=’A’&& ch<=’Z’))  
  22.   
  23.     {  
  24.   
  25.        engishCount++;  
  26.   
  27.     }  
  28.   
  29.     else  
  30.   
  31.     {  
  32.   
  33.        chineseCount++;  
  34.   
  35.     }  
  36.   
  37. }  
  38.   
  39. System.out.println(……………);  
int engishCount;

int chineseCount;

int digitCount;

for(int i=0;i<str.length;i++)

{

    charch = str.charAt(i);

    if(ch>=’0’ && ch<=’9’)

    {

       digitCount++

    }

    elseif((ch>=’a’&& ch<=’z’) ||(ch>=’A’&& ch<=’Z’))

    {

       engishCount++;

    }

    else

    {

       chineseCount++;

    }

}

System.out.println(……………);

这是组合设计模式。

我有很多个(假设10万个)数据要保存起来,以后还需要从保存的这些数据中检索是否存在某个数据,(我想说出二叉树的好处,该怎么说呢?那就是说别人的缺点),假如存在数组中,那么,碰巧要找的数字位于99999那个地方,那查找的速度将很慢,因为要从第1个依次往后取,取出来后进行比较。平衡二叉树(构建平衡二叉树需要先排序,我们这里就不作考虑了)可以很好地解决这个问题,但二叉树的遍历(前序,中序,后序)效率要比数组低很多,原理如下图:

代码如下:

  1. packagecom.huawei.interview;  
  2.   
  3.    
  4.   
  5. public class Node {  
  6.   
  7.    public int value;  
  8.   
  9.    public Node left;  
  10.   
  11.    public Node right;  
  12.   
  13.      
  14.   
  15.    public void store(int value)  
  16.   
  17.    {  
  18.   
  19.       if(value<this.value)  
  20.   
  21.       {  
  22.   
  23.         if(left == null)  
  24.   
  25.         {  
  26.   
  27.            left = new Node();  
  28.   
  29.            left.value=value;  
  30.   
  31.         }  
  32.   
  33.         else  
  34.   
  35.         {  
  36.   
  37.            left.store(value);  
  38.   
  39.         }  
  40.   
  41.       }  
  42.   
  43.       else if(value>this.value)  
  44.   
  45.       {  
  46.   
  47.         if(right == null)  
  48.   
  49.         {  
  50.   
  51.            right = new Node();  
  52.   
  53.            right.value=value;  
  54.   
  55.         }  
  56.   
  57.         else  
  58.   
  59.         {  
  60.   
  61.            right.store(value);  
  62.   
  63.         }         
  64.   
  65.       }  
  66.   
  67.    }  
  68.   
  69.      
  70.   
  71.    public boolean find(int value)  
  72.   
  73.    {    
  74.   
  75.       System.out.println("happen " + this.value);  
  76.   
  77.       if(value == this.value)  
  78.   
  79.       {  
  80.   
  81.         return true;  
  82.   
  83.       }  
  84.   
  85.       else if(value>this.value)  
  86.   
  87.       {  
  88.   
  89.         if(right == nullreturn false;  
  90.   
  91.         return right.find(value);  
  92.   
  93.       }else  
  94.   
  95.       {  
  96.   
  97.         if(left == nullreturn false;  
  98.   
  99.         return left.find(value);  
  100.   
  101.       }  
  102.   
  103.    
  104.   
  105.    }  
  106.   
  107.      
  108.   
  109.    public  void preList()  
  110.   
  111.    {  
  112.   
  113.       System.out.print(this.value + ",");  
  114.   
  115.       if(left!=null) left.preList();  
  116.   
  117.       if(right!=null) right.preList();  
  118.   
  119.    }  
  120.   
  121.      
  122.   
  123.    public void middleList()  
  124.   
  125.    {  
  126.   
  127.       if(left!=null) left.preList();  
  128.   
  129.       System.out.print(this.value + ",");  
  130.   
  131.       if(right!=null) right.preList();     
  132.   
  133.    }  
  134.   
  135.    public void afterList()  
  136.   
  137.    {  
  138.   
  139.       if(left!=null) left.preList();  
  140.   
  141.       if(right!=null) right.preList();  
  142.   
  143.       System.out.print(this.value + ",");     
  144.   
  145.    }    
  146.   
  147.    public static void main(String [] args)  
  148.   
  149.    {  
  150.   
  151.       int [] data = new int[20];  
  152.   
  153.       for(int i=0;i<data.length;i++)  
  154.   
  155.       {  
  156.   
  157.         data[i] = (int)(Math.random()*100) + 1;  
  158.   
  159.         System.out.print(data[i] + ",");  
  160.   
  161.       }  
  162.   
  163.       System.out.println();  
  164.   
  165.         
  166.   
  167.       Node root = new Node();  
  168.   
  169.       root.value = data[0];  
  170.   
  171.       for(int i=1;i<data.length;i++)  
  172.   
  173.       {  
  174.   
  175.         root.store(data[i]);  
  176.   
  177.       }  
  178.   
  179.         
  180.   
  181.       root.find(data[19]);  
  182.   
  183.         
  184.   
  185.       root.preList();  
  186.   
  187.       System.out.println();  
  188.   
  189.       root.middleList();  
  190.   
  191.       System.out.println();      
  192.   
  193.       root.afterList();  
  194.   
  195.    }  
  196.   
  197. }  
  198.   
  199. -----------------又一次临场写的代码---------------------------  
  200.   
  201. import java.util.Arrays;  
  202.   
  203. importjava.util.Iterator;  
  204.   
  205.    
  206.   
  207. public class Node {  
  208.   
  209.    private Node left;  
  210.   
  211.    private Node right;  
  212.   
  213.    private int value;  
  214.   
  215.    //private int num;   
  216.   
  217.      
  218.   
  219.    public Node(int value){  
  220.   
  221.       this.value = value;  
  222.   
  223.    }  
  224.   
  225.    public void add(int value){  
  226.   
  227.         
  228.   
  229.       if(value > this.value)  
  230.   
  231.       {  
  232.   
  233.         if(right != null)  
  234.   
  235.            right.add(value);  
  236.   
  237.         else  
  238.   
  239.         {  
  240.   
  241.            Node node = new Node(value);             
  242.   
  243.            right = node;  
  244.   
  245.         }  
  246.   
  247.       }  
  248.   
  249.       else{  
  250.   
  251.         if(left != null)  
  252.   
  253.            left.add(value);  
  254.   
  255.         else  
  256.   
  257.         {  
  258.   
  259.            Node node = new Node(value);             
  260.   
  261.            left = node;  
  262.   
  263.         }         
  264.   
  265.       }  
  266.   
  267.    }  
  268.   
  269.      
  270.   
  271.    public boolean find(int value){  
  272.   
  273.       if(value == this.value) return true;  
  274.   
  275.       else if(value > this.value){  
  276.   
  277.         if(right == nullreturn false;  
  278.   
  279.         else return right.find(value);  
  280.   
  281.       }else{  
  282.   
  283.         if(left == nullreturn false;  
  284.   
  285.         else return left.find(value);         
  286.   
  287.       }  
  288.   
  289.    
  290.   
  291.    }  
  292.   
  293.      
  294.   
  295.    public void display(){  
  296.   
  297.       System.out.println(value);  
  298.   
  299.       if(left != null) left.display();  
  300.   
  301.       if(right != null) right.display();  
  302.   
  303.         
  304.   
  305.    }  
  306.   
  307.      
  308.   
  309.    /*public Iterator iterator(){ 
  310.  
  311.        
  312.  
  313.    }*/  
  314.   
  315.      
  316.   
  317.    public static void main(String[] args){  
  318.   
  319.       int[] values = new int[8];  
  320.   
  321.       for(int i=0;i<8;i++){  
  322.   
  323.         int num = (int)(Math.random() * 15);  
  324.   
  325.         //System.out.println(num);   
  326.   
  327.         //if(Arrays.binarySearch(values, num)<0)   
  328.   
  329.         if(!contains(values,num))  
  330.   
  331.            values[i] = num;  
  332.   
  333.         else  
  334.   
  335.            i--;  
  336.   
  337.       }  
  338.   
  339.         
  340.   
  341.       System.out.println(Arrays.toString(values));  
  342.   
  343.         
  344.   
  345.       Node root  = newNode(values[0]);  
  346.   
  347.       for(int i=1;i<values.length;i++){  
  348.   
  349.         root.add(values[i]);  
  350.   
  351.       }  
  352.   
  353.         
  354.   
  355.       System.out.println(root.find(13));  
  356.   
  357.         
  358.   
  359.       root.display();  
  360.   
  361.         
  362.   
  363.    }  
  364.   
  365.      
  366.   
  367.    public static boolean contains(int [] arr, int value){  
  368.   
  369.       int i = 0;  
  370.   
  371.       for(;i<arr.length;i++){  
  372.   
  373.         if(arr[i] == value) return true;  
  374.   
  375.           
  376.   
  377.       }  
  378.   
  379.       return false;  
  380.   
  381.    }  
  382.   
  383.      
  384.   
  385. }  
packagecom.huawei.interview;

 

public class Node {

   public int value;

   public Node left;

   public Node right;

   

   public void store(int value)

   {

      if(value<this.value)

      {

        if(left == null)

        {

           left = new Node();

           left.value=value;

        }

        else

        {

           left.store(value);

        }

      }

      else if(value>this.value)

      {

        if(right == null)

        {

           right = new Node();

           right.value=value;

        }

        else

        {

           right.store(value);

        }       

      }

   }

   

   public boolean find(int value)

   {  

      System.out.println("happen " + this.value);

      if(value == this.value)

      {

        return true;

      }

      else if(value>this.value)

      {

        if(right == null) return false;

        return right.find(value);

      }else

      {

        if(left == null) return false;

        return left.find(value);

      }

 

   }

   

   public  void preList()

   {

      System.out.print(this.value + ",");

      if(left!=null) left.preList();

      if(right!=null) right.preList();

   }

   

   public void middleList()

   {

      if(left!=null) left.preList();

      System.out.print(this.value + ",");

      if(right!=null) right.preList();   

   }

   public void afterList()

   {

      if(left!=null) left.preList();

      if(right!=null) right.preList();

      System.out.print(this.value + ",");   

   }  

   public static void main(String [] args)

   {

      int [] data = new int[20];

      for(int i=0;i<data.length;i++)

      {

        data[i] = (int)(Math.random()*100) + 1;

        System.out.print(data[i] + ",");

      }

      System.out.println();

      

      Node root = new Node();

      root.value = data[0];

      for(int i=1;i<data.length;i++)

      {

        root.store(data[i]);

      }

      

      root.find(data[19]);

      

      root.preList();

      System.out.println();

      root.middleList();

      System.out.println();    

      root.afterList();

   }

}

-----------------又一次临场写的代码---------------------------

import java.util.Arrays;

importjava.util.Iterator;

 

public class Node {

   private Node left;

   private Node right;

   private int value;

   //private int num;

   

   public Node(int value){

      this.value = value;

   }

   public void add(int value){

      

      if(value > this.value)

      {

        if(right != null)

           right.add(value);

        else

        {

           Node node = new Node(value);           

           right = node;

        }

      }

      else{

        if(left != null)

           left.add(value);

        else

        {

           Node node = new Node(value);           

           left = node;

        }       

      }

   }

   

   public boolean find(int value){

      if(value == this.value) return true;

      else if(value > this.value){

        if(right == null) return false;

        else return right.find(value);

      }else{

        if(left == null) return false;

        else return left.find(value);       

      }

 

   }

   

   public void display(){

      System.out.println(value);

      if(left != null) left.display();

      if(right != null) right.display();

      

   }

   

   /*public Iterator iterator(){

      

   }*/

   

   public static void main(String[] args){

      int[] values = new int[8];

      for(int i=0;i<8;i++){

        int num = (int)(Math.random() * 15);

        //System.out.println(num);

        //if(Arrays.binarySearch(values, num)<0)

        if(!contains(values,num))

           values[i] = num;

        else

           i--;

      }

      

      System.out.println(Arrays.toString(values));

      

      Node root  = newNode(values[0]);

      for(int i=1;i<values.length;i++){

        root.add(values[i]);

      }

      

      System.out.println(root.find(13));

      

      root.display();

      

   }

   

   public static boolean contains(int [] arr, int value){

      int i = 0;

      for(;i<arr.length;i++){

        if(arr[i] == value) return true;

        

      }

      return false;

   }

   

}


 

1、从类似如下的文本文件中读取出所有的姓名,并打印出重复的姓名和重复的次数,并按重复次数排序:

1,张三,28

2,李四,35

3,张三,28

4,王五,35

5,张三,28

6,李四,35

7,赵六,28

8,田七,35

程序代码如下(答题要博得用人单位的喜欢,包名用该公司,面试前就提前查好该公司的网址,如果查不到,现场问也是可以的。还要加上实现思路的注释):

  1. packagecom.huawei.interview;  
  2.   
  3.    
  4.   
  5. importjava.io.BufferedReader;  
  6.   
  7. import java.io.IOException;  
  8.   
  9. importjava.io.InputStream;  
  10.   
  11. importjava.io.InputStreamReader;  
  12.   
  13. importjava.util.Comparator;  
  14.   
  15. importjava.util.HashMap;  
  16.   
  17. importjava.util.Iterator;  
  18.   
  19. importjava.util.Map;  
  20.   
  21. importjava.util.TreeSet;  
  22.   
  23.    
  24.   
  25.    
  26.   
  27. public class GetNameTest {  
  28.   
  29.    
  30.   
  31.    /** 
  32.  
  33.     * @param args 
  34.  
  35.     */  
  36.   
  37.    public static void main(String[] args) {  
  38.   
  39.       // TODOAuto-generated method stub   
  40.   
  41.       //InputStream ips =GetNameTest.class.getResourceAsStream("/com/huawei/interview/info.txt");   
  42.   
  43.       //用上一行注释的代码和下一行的代码都可以,因为info.txt与GetNameTest类在同一包下面,所以,可以用下面的相对路径形式   
  44.   
  45.         
  46.   
  47.       Map results = new HashMap();  
  48.   
  49.       InputStream ips = GetNameTest.class.getResourceAsStream("info.txt");  
  50.   
  51.       BufferedReader in = new BufferedReader(new InputStreamReader(ips));  
  52.   
  53.       String line = null;  
  54.   
  55.       try {  
  56.   
  57.         while((line=in.readLine())!=null)  
  58.   
  59.         {  
  60.   
  61.            dealLine(line,results);  
  62.   
  63.         }  
  64.   
  65.         sortResults(results);  
  66.   
  67.       } catch (IOException e) {  
  68.   
  69.         // TODO Auto-generated catch block   
  70.   
  71.         e.printStackTrace();  
  72.   
  73.       }  
  74.   
  75.    }  
  76.   
  77.      
  78.   
  79.    static class User  
  80.   
  81.    {  
  82.   
  83.       public String name;  
  84.   
  85.       public Integer value;  
  86.   
  87.       public User(String name,Integer value)  
  88.   
  89.       {  
  90.   
  91.         this.name = name;  
  92.   
  93.         this.value = value;  
  94.   
  95.       }  
  96.   
  97.    
  98.   
  99.       @Override  
  100.   
  101.       public boolean equals(Object obj) {  
  102.   
  103.         // TODO Auto-generated method stub   
  104.   
  105.              
  106.   
  107.         //下面的代码没有执行,说明往treeset中增加数据时,不会使用到equals方法。   
  108.   
  109.         boolean result = super.equals(obj);  
  110.   
  111.         System.out.println(result);  
  112.   
  113.         return result;  
  114.   
  115.       }  
  116.   
  117.    }  
  118.   
  119.      
  120.   
  121.    private static void sortResults(Map results) {  
  122.   
  123.       // TODOAuto-generated method stub   
  124.   
  125.       TreeSet sortedResults = new TreeSet(  
  126.   
  127.            new Comparator(){  
  128.   
  129.               public int compare(Object o1, Object o2) {  
  130.   
  131.                  // TODO Auto-generated method stub   
  132.   
  133.                  User user1 = (User)o1;  
  134.   
  135.                  User user2 = (User)o2;  
  136.   
  137.                  /*如果compareTo返回结果0,则认为两个对象相等,新的对象不会增加到集合中去 
  138.  
  139.                   * 所以,不能直接用下面的代码,否则,那些个数相同的其他姓名就打印不出来。 
  140.  
  141.                   * */  
  142.   
  143.                    
  144.   
  145.                  //return user1.value-user2.value;   
  146.   
  147.                  //returnuser1.value<user2.value?-1:user1.value==user2.value?0:1;   
  148.   
  149.                  if(user1.value<user2.value)  
  150.   
  151.                  {  
  152.   
  153.                     return -1;  
  154.   
  155.                  }else if(user1.value>user2.value)  
  156.   
  157.                  {  
  158.   
  159.                     return 1;  
  160.   
  161.                  }else  
  162.   
  163.                  {  
  164.   
  165.                     return user1.name.compareTo(user2.name);  
  166.   
  167.                  }  
  168.   
  169.               }  
  170.   
  171.                 
  172.   
  173.            }  
  174.   
  175.       );  
  176.   
  177.       Iterator iterator =results.keySet().iterator();  
  178.   
  179.       while(iterator.hasNext())  
  180.   
  181.       {  
  182.   
  183.         String name = (String)iterator.next();  
  184.   
  185.         Integer value =(Integer)results.get(name);  
  186.   
  187.         if(value > 1)  
  188.   
  189.         {            
  190.   
  191.            sortedResults.add(new User(name,value));           
  192.   
  193.         }  
  194.   
  195.       }  
  196.   
  197.         
  198.   
  199.       printResults(sortedResults);  
  200.   
  201.    }  
  202.   
  203.    private static void printResults(TreeSet sortedResults)  
  204.   
  205.    {  
  206.   
  207.       Iterator iterator  = sortedResults.iterator();  
  208.   
  209.       while(iterator.hasNext())  
  210.   
  211.       {  
  212.   
  213.         User user = (User)iterator.next();  
  214.   
  215.         System.out.println(user.name + ":" + user.value);  
  216.   
  217.       }    
  218.   
  219.    }  
  220.   
  221.    public static void dealLine(String line,Map map)  
  222.   
  223.    {  
  224.   
  225.       if(!"".equals(line.trim()))  
  226.   
  227.       {  
  228.   
  229.         String [] results = line.split(",");  
  230.   
  231.         if(results.length == 3)  
  232.   
  233.         {  
  234.   
  235.            String name = results[1];  
  236.   
  237.            Integer value =(Integer)map.get(name);  
  238.   
  239.            if(value == null) value = 0;  
  240.   
  241.            map.put(name,value + 1);  
  242.   
  243.         }  
  244.   
  245.       }  
  246.   
  247.    }  
  248.   
  249.    
  250.   
  251. }  
  252.   
  253. 48、写一个Singleton出来。  
  254.   
  255. 第一种:饱汉模式  
  256.   
  257. public classSingleTon {  
  258.   
  259.    private SingleTon(){  
  260.   
  261.       }  
  262.   
  263.    
  264.   
  265.    //实例化放在静态代码块里可提高程序的执行效率,但也可能更占用空间     
  266.   
  267.    private final static SingleTon instance = newSingleTon();  
  268.   
  269.    public static SingleTon getInstance(){  
  270.   
  271.       return instance;  
  272.   
  273.    }  
  274.   
  275. }  
  276.   
  277.    
  278.   
  279. 第二种:饥汉模式  
  280.   
  281. public classSingleTon {  
  282.   
  283.    private SingleTon(){}  
  284.   
  285.      
  286.   
  287.    private static instance = null;//newSingleTon();   
  288.   
  289.      
  290.   
  291.    public static synchronized SingleTongetInstance(){  
  292.   
  293.       if(instance == null)  
  294.   
  295.         instance = new SingleTon();  
  296.   
  297.       return instance;  
  298.   
  299.    }  
  300.   
  301. }  
  302.   
  303.    
  304.   
  305. 第三种:用枚举  
  306.   
  307.    public enum SingleTon{  
  308.   
  309.       ONE;  
  310.   
  311.      
  312.   
  313.    }  
  314.   
  315.    
  316.   
  317. 第三:更实际的应用(在什么情况用单例)  
  318.   
  319. public classSequenceGenerator{  
  320.   
  321.    //下面是该类自身的业务功能代码   
  322.   
  323.    private int count = 0;  
  324.   
  325.    
  326.   
  327.    public synchronized int getSequence(){  
  328.   
  329.       ++count;  
  330.   
  331.    }  
  332.   
  333.      
  334.   
  335.    //下面是把该类变成单例的代码   
  336.   
  337.    private SequenceGenerator(){}  
  338.   
  339.    private final static instance = new SequenceGenerator();  
  340.   
  341.    public static SingleTon getInstance(){  
  342.   
  343.       return instance;  
  344.   
  345.    }    
  346.   
  347.      
  348.   
  349. }  
  350.   
  351.    
  352.   
  353. 第四:  
  354.   
  355.    public class MemoryDao  
  356.   
  357.    {  
  358.   
  359.     private HashMap map = new HashMap();  
  360.   
  361.       
  362.   
  363.     publicvoid add(Student stu1){   
  364.   
  365.          map.put(SequenceGenerator.getInstance().getSequence(),stu1);  
  366.   
  367.     }  
  368.   
  369.      
  370.   
  371.    //把MemoryDao变成单例    
  372.   
  373.   }  
  374.   
  375.    
  376.   
  377.    
  378.   
  379.    
  380.   
  381.    
  382.   
  383.    
  384.   
  385.    
  386.   
  387. Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。   
  388.   
  389. 一般Singleton模式通常有几种种形式:   
  390.   
  391. 第一种形式: 定义一个类,它的构造函数为private的,它有一个staticprivate的该类变量,在类初始化时实例话,通过一个public的getInstance方法获取对它的引用,继而调用其中的方法。  
  392.   
  393. public class Singleton {   
  394.   
  395. private Singleton(){}   
  396.   
  397.       //在自己内部定义自己一个实例,是不是很奇怪?    
  398.   
  399.       //注意这是private 只供内部调用    
  400.   
  401.       private static Singleton instance = newSingleton();   
  402.   
  403.       //这里提供了一个供外部访问本class的静态方法,可以直接访问      
  404.   
  405.       public static Singleton getInstance() {   
  406.   
  407.         return instance;      
  408.   
  409.       }   
  410.   
  411.    }   
  412.   
  413.    第二种形式:   
  414.   
  415. public class Singleton {   
  416.   
  417.   private staticSingleton instance = null;   
  418.   
  419.   public staticsynchronized Singleton getInstance() {   
  420.   
  421.   //这个方法比上面有所改进,不用每次都进行生成对象,只是第一次         
  422.   
  423.   //使用时生成实例,提高了效率!    
  424.   
  425.   if(instance==null)   
  426.   
  427.     instance=new Singleton();   
  428.   
  429.                returninstance;     
  430.   
  431.    }   
  432.   
  433. }   
  434.   
  435. 其他形式:   
  436.   
  437. 定义一个类,它的构造函数为private的,所有方法为static的。   
  438.   
  439. 一般认为第一种形式要更加安全些   
packagecom.huawei.interview;

 

importjava.io.BufferedReader;

import java.io.IOException;

importjava.io.InputStream;

importjava.io.InputStreamReader;

importjava.util.Comparator;

importjava.util.HashMap;

importjava.util.Iterator;

importjava.util.Map;

importjava.util.TreeSet;

 

 

public class GetNameTest {

 

   /**

    * @param args

    */

   public static void main(String[] args) {

      // TODOAuto-generated method stub

      //InputStream ips =GetNameTest.class.getResourceAsStream("/com/huawei/interview/info.txt");

      //用上一行注释的代码和下一行的代码都可以,因为info.txt与GetNameTest类在同一包下面,所以,可以用下面的相对路径形式

      

      Map results = new HashMap();

      InputStream ips = GetNameTest.class.getResourceAsStream("info.txt");

      BufferedReader in = new BufferedReader(new InputStreamReader(ips));

      String line = null;

      try {

        while((line=in.readLine())!=null)

        {

           dealLine(line,results);

        }

        sortResults(results);

      } catch (IOException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

      }

   }

   

   static class User

   {

      public String name;

      public Integer value;

      public User(String name,Integer value)

      {

        this.name = name;

        this.value = value;

      }

 

      @Override

      public boolean equals(Object obj) {

        // TODO Auto-generated method stub

           

        //下面的代码没有执行,说明往treeset中增加数据时,不会使用到equals方法。

        boolean result = super.equals(obj);

        System.out.println(result);

        return result;

      }

   }

   

   private static void sortResults(Map results) {

      // TODOAuto-generated method stub

      TreeSet sortedResults = new TreeSet(

           new Comparator(){

              public int compare(Object o1, Object o2) {

                 // TODO Auto-generated method stub

                 User user1 = (User)o1;

                 User user2 = (User)o2;

                 /*如果compareTo返回结果0,则认为两个对象相等,新的对象不会增加到集合中去

                  * 所以,不能直接用下面的代码,否则,那些个数相同的其他姓名就打印不出来。

                  * */

                 

                 //return user1.value-user2.value;

                 //returnuser1.value<user2.value?-1:user1.value==user2.value?0:1;

                 if(user1.value<user2.value)

                 {

                    return -1;

                 }else if(user1.value>user2.value)

                 {

                    return 1;

                 }else

                 {

                    return user1.name.compareTo(user2.name);

                 }

              }

              

           }

      );

      Iterator iterator =results.keySet().iterator();

      while(iterator.hasNext())

      {

        String name = (String)iterator.next();

        Integer value =(Integer)results.get(name);

        if(value > 1)

        {          

           sortedResults.add(new User(name,value));         

        }

      }

      

      printResults(sortedResults);

   }

   private static void printResults(TreeSet sortedResults)

   {

      Iterator iterator  = sortedResults.iterator();

      while(iterator.hasNext())

      {

        User user = (User)iterator.next();

        System.out.println(user.name + ":" + user.value);

      }  

   }

   public static void dealLine(String line,Map map)

   {

      if(!"".equals(line.trim()))

      {

        String [] results = line.split(",");

        if(results.length == 3)

        {

           String name = results[1];

           Integer value =(Integer)map.get(name);

           if(value == null) value = 0;

           map.put(name,value + 1);

        }

      }

   }

 

}

48、写一个Singleton出来。

第一种:饱汉模式

public classSingleTon {

   private SingleTon(){

      }

 

   //实例化放在静态代码块里可提高程序的执行效率,但也可能更占用空间  

   private final static SingleTon instance = newSingleTon();

   public static SingleTon getInstance(){

      return instance;

   }

}

 

第二种:饥汉模式

public classSingleTon {

   private SingleTon(){}

   

   private static instance = null;//newSingleTon();

   

   public static synchronized SingleTongetInstance(){

      if(instance == null)

        instance = new SingleTon();

      return instance;

   }

}

 

第三种:用枚举

   public enum SingleTon{

      ONE;

   

   }

 

第三:更实际的应用(在什么情况用单例)

public classSequenceGenerator{

   //下面是该类自身的业务功能代码

   private int count = 0;

 

   public synchronized int getSequence(){

      ++count;

   }

   

   //下面是把该类变成单例的代码

   private SequenceGenerator(){}

   private final static instance = new SequenceGenerator();

   public static SingleTon getInstance(){

      return instance;

   }  

   

}

 

第四:

   public class MemoryDao

   {

    private HashMap map = new HashMap();

    

    publicvoid add(Student stu1){ 

         map.put(SequenceGenerator.getInstance().getSequence(),stu1);

    }

   

   //把MemoryDao变成单例 

  }

 

 

 

 

 

 

Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。 

一般Singleton模式通常有几种种形式: 

第一种形式: 定义一个类,它的构造函数为private的,它有一个static的private的该类变量,在类初始化时实例话,通过一个public的getInstance方法获取对它的引用,继而调用其中的方法。

public class Singleton { 

private Singleton(){} 

      //在自己内部定义自己一个实例,是不是很奇怪? 

      //注意这是private 只供内部调用 

      private static Singleton instance = newSingleton(); 

      //这里提供了一个供外部访问本class的静态方法,可以直接访问   

      public static Singleton getInstance() { 

        return instance;    

      } 

   } 

   第二种形式: 

public class Singleton { 

  private staticSingleton instance = null; 

  public staticsynchronized Singleton getInstance() { 

  //这个方法比上面有所改进,不用每次都进行生成对象,只是第一次      

  //使用时生成实例,提高了效率! 

  if(instance==null) 

    instance=new Singleton(); 

               returninstance;   

   } 

} 

其他形式: 

定义一个类,它的构造函数为private的,所有方法为static的。 

一般认为第一种形式要更加安全些 

 

原文地址:https://www.cnblogs.com/gxpblogs/p/3068815.html