`
cleverbing
  • 浏览: 14978 次
  • 性别: Icon_minigender_1
  • 来自: 火星
社区版块
存档分类
最新评论

java 算法

 
阅读更多

<!-- [if gte mso 9]><xml><w:WordDocument><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><w:DisplayHorizontalDrawingGridEvery>0</w:DisplayHorizontalDrawingGridEvery><w:DisplayVerticalDrawingGridEvery>2</w:DisplayVerticalDrawingGridEvery><w:DocumentKind>DocumentNotSpecified</w:DocumentKind><w:DrawingGridVerticalSpacing>7.8</w:DrawingGridVerticalSpacing><w:View>Normal</w:View><w:Compatibility></w:Compatibility><w:Zoom>0</w:Zoom></w:WordDocument></xml><![endif]-->

算法与编程

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

答:

package cn.itcast;

 

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

 

public class MainClass{

public static void main(String[] args) throws Exception{

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

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

FileWriter c = new FileWriter("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(String filename,char[] seperators) throws Exception{

File f = new File(filename);

FileReader reader = new FileReader(f);

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

int len = reader.read(buf);

String results = new String(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++];

}

 

}

 

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

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

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

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 void main(String[] args) throws Exception {

File srcDir = new File("java");

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

throw new Exception("目录不存在 ");

File[] files = srcDir.listFiles(

new FilenameFilter(){

 

public boolean accept(File dir, String name) {

return name.endsWith(".java");

}

}

);

System.out.println(files.length);

File destDir = new File("jad");

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

for(File f :files){

FileInputStream  fis = new FileInputStream(f);

String destFileName = f.getName().replaceAll("\\.java$", ".jad");

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

copy(fis,fos);

fis.close();

fos.close();

}

}

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

int len = 0;

byte[] buf = new byte[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 的文件:  class MyFileFilter implememyts FileFilter{

public boolean accept(File pathname){

return pathname.getName().endsWith(".java")

}

}

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

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

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

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

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

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

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

}

 

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

File[] listFiles(FileFilter filter){

File[] files = listFiles();

//Arraylist acceptedFilesList = new ArrayList();

File[] acceptedFiles = new File[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 为要截取的字节数。

public static void main(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;

boolean bChineseFirstHalf = false;

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

{

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

bChineseFirstHalf = true;

}else{

num++;

bChineseFirstHalf = false;

}

}

return num;

}

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

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

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" 要分别统计英文字符的数量,中文字符的数量,和数字字符的数量,假设字符中没有中文字符、英文字符、数字字符之外的其他特殊字符。

int engishCount;

int chineseCount;

int digitCount;

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

{

char ch = str.charAt(i);

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

{

digitCount++

}

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

{

engishCount++;

}

else

{

chineseCount++;

}

}

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

 

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

这是组合设计模式。

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

 

代码如下:

package com.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;

import java.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  = new Node(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;

}

}

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

1,张三 ,28

2,李四 ,35

3,张三 ,28

4,王五 ,35

5,张三 ,28

6,李四 ,35

7,赵六 ,28

8,田七 ,35

 

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

package com.huawei.interview;

 

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.util.Comparator;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import java.util.TreeSet;

 

 

public class GetNameTest {

 

/**

 * @param args

 */

public static void main(String[] args) {

// TODO Auto-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) {

// TODO Auto-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;

//return user1.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);

}

}

}

 

}

8、递归算法题 1

一个整数,大于0 ,不用循环和本地变量,按照 n 2n 4n 8n 的顺序递增,当值大于 5000 时,把值按照指定顺序输出来。

例:n=1237

则输出为:

1237

2474

4948

9896

9896

4948

2474

1237

提示:写程序时,先致谢按递增方式的代码,写好递增的以后,再增加考虑递减部分。

public static void doubleNum(int n)

{

System.out.println(n);

if(n<=5000)

doubleNum(n*2);

System.out.println(n);

}

 

 

9、递归算法题 2

1 个人 10 ,第 2 个比第 1 个人大 2 岁,依次递推,请用递归方式计算出第 8 个人多大?

package cn.itcast;

 

import java.util.Date;

 

public class A1 {

 

public static void main(String [] args)

{

System.out.println(computeAge(8));

}

public static int computeAge(int n)

{

if(n==1) return 10;

return computeAge(n-1) + 2;

}

}

 

public static void toBinary(int n,StringBuffer result)

{

 

if(n/2 != 0)

toBinary(n/2,result);

result.append(n%2);

}

10、排序都有哪几种方法?请列举。用 JAVA 实现一个快速排序。 

 本人只研究过冒泡排序、选择排序和快速排序,下面是快速排序的代码:

public class QuickSort {

/**

快速排序

* @param strDate

* @param left

* @param right

*/

public void quickSort(String[] strDate,int left,int right){

String middle,tempDate;

int i,j;

i=left;

j=right;

middle=strDate[(i+j)/2];

do{

while(strDate[i].compareTo(middle)<0&& i<right)

i++; //找出左边比中间值大的数

while(strDate[j].compareTo(middle)>0&& j>left)

j--; //找出右边比中间值小的数

if(i<=j){ //将左边大的数和右边小的数进行替换 

tempDate=strDate[i];

strDate[i]=strDate[j];

strDate[j]=tempDate;

i++;

j--;

}

}while(i<=j); //当两者交错时停止

 

if(i<right){

quickSort(strDate,i,right);//

}

if(j>left){

quickSort(strDate,left,j);

}

}

/**

  * @param args

  */

public static void main(String[] args){

String[] strVoid=new String[]{"11","66","22","0","55","22","0","32"};

QuickSort sort=new QuickSort();

sort.quickSort(strVoid,0,strVoid.length-1);

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

System.out.println(strVoid[i]+" ");

}

}

 

 

}

11、有数组 a[n] ,用 java 代码将数组元素顺序颠倒

//用下面的也可以

//for(int i=0,int j=a.length-1;i<j;i++,j--) 是否等效于  for(int i=0;i<a.length/2;i++) 呢?

 

import java.util.Arrays;

 

public class SwapDemo{

 

public static void main(String[] args){

int [] a = new int[]{

(int)(Math.random() * 1000),

(int)(Math.random() * 1000),

(int)(Math.random() * 1000),

(int)(Math.random() * 1000),

(int)(Math.random() * 1000)

};

System.out.println(a);

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

swap(a);

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

}

public static void swap(int a[]){

int len = a.length;

for(int i=0;i<len/2;i++){

int tmp = a[i];

a[i] = a[len-1-i];

a[len-1-i] = tmp;

}

}

}

12.金额转换,阿拉伯数字的金额转换成中国传统的形式如:(¥ 1011 )- > (一千零一拾一元整)输出。

去零的代码:

return sb.reverse().toString().replaceAll(" [ 拾佰仟 ]"," ").replaceAll(" + "," ").replaceAll(" + "," ").replaceAll(" +"," ");

 

public class RenMingBi {

 

/**

 * @param args add by zxx ,Nov 29, 2008

 */

private static final char[] data = new char[]{

' ',' ',' ',' ',' ',' ',' ',' ',' ',' '

}; 

private static final char[] units = new char[]{

' ',' ',' ',' ',' ',' ',' ',' ',' 亿 '

};

public static void main(String[] args) {

// TODO Auto-generated method stub

System.out.println(

convert(135689123));

}

 

public static String convert(int money)

{

StringBuffer sbf = new StringBuffer();

int unit = 0;

while(money!=0)

{

sbf.insert(0,units[unit++]);

int number = money%10;

sbf.insert(0, data[number]);

money /= 10;

}

 

return sbf.toString();

}

}

 

 

 

 

 

该公司笔试题就1 个,要求在 10 分钟内作完。

    题目如下:用1 2 2 3 4 5 这六个数字,用 java 写一个 main 函数,打印出所有不同的排列,如: 512234 412345 等,要求: "4" 不能在第三位, "3" "5" 不能相连。



static int[] bits = new int[] { 1, 2, 3, 4, 5 };

/**
 * @param args
 */
public static void main(String[] args) {
sort("", bits);
}

private static void sort(String prefix, int[] a) {
if (a.length == 1) {
System.out.println(prefix + a[0]);
}

for (int i = 0; i < a.length; i++) {
sort(prefix + a[i], copy(a, i));
}
}

private static int[] copy(int[] a,int index){
int[] b = new int[a.length-1];
System.arraycopy(a, 0, b, 0, index);
System.arraycopy(a, index+1, b, index, a.length-index-1);
return b;
}


**********************************************************************

  基本思路:
把问题归结为图结构的遍历问题。实际上 6 个数字就是六个结点,把六个结点连接成无向连通图,对于每一个结点求这个图形的遍历路径,所有结点的遍历路径就是最后对这 6 个数字的排列组合结果集。
显然这个结果集还未达到题目的要求。从以下几个方面考虑:
  1. 3 5 不能相连:实际要求这个连通图的结点 3 5 之间不能连通 可在构造图结构时就满足改条件,然后再遍历图。
  2. 不能有重复 考虑到有两个 2 ,明显会存在重复结果,可以把结果集放在 TreeSet 中过滤重复结果
  3. 4不能在第三位 仍旧在结果集中去除满足此条件的结果。

采用二维数组定义图结构,最后的代码是:

import java.util.Iterator;
import java.util.TreeSet;

public class TestQuestion {

private String[] b = new String[]{"1", "2", "2", "3", "4", "5"};
private int n = b.length;
private boolean[] visited = new boolean[n];
private int[][] a = new int[n][n];
private String result = "";
private TreeSet set = new TreeSet();

public static void main(String[] args) {
new TestQuestion().start();
}

private void start() {

// Initial the map a[][]
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
a[i][j] = 0;
} else {
    a[i][j] = 1;
}
}
}

// 3 and 5 can not be the neighbor.
a[3][5] = 0;
a[5][3] = 0;

// Begin to depth  search.
for (int i = 0; i < n; i++) {
    this.depthFirstSearch(i);
}

// Print result treeset.
Iterator it = set.iterator();
while (it.hasNext()) {
String string = (String) it.next();
// "4" can not be the third position.
if (string.indexOf("4") != 2) {
System.out.println(string);
}
}
}

private void depthFirstSearch(int startIndex) {
visited[startIndex] = true;
result = result + b[startIndex];
if (result.length() == n) {
// Filt the duplicate value.
set.add(result);
}
for(int j = 0; j < n; j++) {
if (a[startIndex][j] == 1 && visited[j] == false) {
depthFirstSearch(j);
} else {
continue;
}
}

// restore the result value and visited value after listing a node.
    result = result.substring(0, result.length() -1);
    visited[startIndex] = false;
}
}

 

posted on 2007-03-04 14:17  Bill111  阅读(7059)  评论(6)    编辑    收藏

 

评论

#   re: Java经典算法集  2007-03-25 08:27  圆规 

大家好好看看吧! 加油哦 !

   回复    更多评论      

#   re: Java经典算法集  2008-09-06 10:45 123 

好啊好啊

   回复    更多评论      

#   re: Java经典算法集  2008-10-22 20:11 cc-yuechuzhao 

我的算法,不用任何数据结构
public class choose6 {
public static void main(String[] args) {
int t=0;
int x;
for (x = 122345; x < 543222; x++) {
if ((x + "").indexOf('2') >= 0) {
if ((x + "").indexOf('2', (x + "").indexOf('2')) >= 0) {
if (((x + "").indexOf('3') >= 0)
&& ((x + "").indexOf('4') >= 0)
&& ((x + "").indexOf('5') >= 0)
&&((x + "").indexOf("35")<0)
&&((x + "").indexOf("53")<0)
&&((x + "").indexOf('4')!=2)
)
++t;
System.out.println(x);
}
}
}System.out.println(t);
}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics