1. 程式人生 > >java面試題彙總(二)----演算法與程式設計

java面試題彙總(二)----演算法與程式設計

1、編寫一個程式,將a.txt檔案中的單詞與b.txt檔案中的單詞交替合併到c.txt檔案中,a.txt檔案中的單詞用回車符分隔,b.txt檔案中用回車或空格進行分隔。

答:

package com.bwie.interview;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintStream;

import java.util.StringTokenizer;

public class AnswerB01 {

    public static void

main(String[] args) throws IOException {

        StringTokenizer tokenizer1 = getTokenzer("/a.txt");

        StringTokenizer tokenizer2 = getTokenzer("/b.txt");

        PrintStream out = new PrintStream("C:/c.txt");

        while (tokenizer1.hasMoreTokens() && tokenizer2.hasMoreTokens()) {

            out.println(tokenizer1.nextToken());

            out.println(tokenizer2.nextToken());

        }

        out.close();

    }

    private static StringTokenizer getTokenzer(String fileName) throws IOException {

        InputStreamReader reader = new InputStreamReader(AnswerB01.class

.getResourceAsStream(fileName));

        StringBuilder builder = new StringBuilder(1000);

        int length = -1;

        char[] cs = new char[1024];

        while ((length = reader.read(cs)) != -1) {

            builder.append(cs, 0, length);

        }

        reader.close();

        return new StringTokenizer(builder.toString());

    }

}

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;

public class AnswerB02 {

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

        File sourceFolder = new File("D:/java");

        File[] files = sourceFolder.listFiles(new JavaFileFilter());

        for (File file : files) {

            String absolutePath = file.getName();

            String targetFile = "D:/jad/" + absolutePath.substring(0, absolutePath.length() - 5) + ".jad";

            copy(file, new File(targetFile));

        }

    }

    private static void copy(File source, File target) throws IOException {

        FileInputStream input = new FileInputStream(source);

        FileOutputStream out = new FileOutputStream(target);

        int length = -1;

        byte[] bs = new byte[1024];

        while ((length = input.read(bs)) != -1) {

            out.write(bs, 0, length);

        }

        input.close();

        out.close();

    }

private static final class JavaFileFilter implements FilenameFilter {

        @Override

        public boolean accept(File dir, String name) {

            return name.endsWith(".java");

        }

    }

}

3、編寫一個擷取字串的函式,輸入為一個字串和位元組數,輸出為按位元組擷取的字串,但要保證漢字不被擷取半個,如“我ABC”,4,應該擷取“我AB”,輸入“我ABC漢DEF”,6,應該輸出“我ABC”,而不是“我ABC+漢的半個”。

import java.io.IOException;

public class AnswerB03 {

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

        String s = "我ABC漢DEF";

        System.out.println(substring(s, 6));

    }

    public static String substring(String s, int length) {

        char[] cs = s.toCharArray();

        StringBuilder builder = new StringBuilder();

        int count = 0;

        for (char c : cs) {

            if (isAsc(c)) {

                count++;

            } else {

                count += 2;

            }

            if (count > length) {

                break;

            }

            builder.append(c);

        }

        return builder.toString();

    }

    public static boolean isAsc(char c) {

        return c < 128;

    }

}

 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++;

    }

}

5、說明生活中遇到的二叉樹,用java實現二叉樹

這是組合設計模式。

我有很多個(假設10萬個)資料要儲存起來,以後還需要從儲存的這些資料中檢索是否存在某個資料,(我想說出二叉樹的好處,該怎麼說呢?那就是說別人的缺點),假如存在陣列中,那麼,碰巧要找的數字位於99999那個地方,那查詢的速度將很慢,因為要從第1個依次往後取,取出來後進行比較。平衡二叉樹(構建平衡二叉樹需要先排序,我們這裡就不作考慮了)可以很好地解決這個問題,但二叉樹的遍歷(前序,中序,後序)效率要比陣列低很多,原理如下圖:

程式碼如下:

public class AnswerB04 {

    public static void main(String[] args) {

        Node root = makeupTree();

        traverse(root);

    }

    private static void traverse(Node node) {

        if (node == null) {

            return;

        }

        traverse(node.left);

        System.out.println(node.value);

        traverse(node.right);

    }

    private static Node makeupTree() {

        Node root = new Node(0);

        Node node1 = new Node(1);

        Node node2 = new Node(2);

        Node node11 = new Node(11);

        Node node12 = new Node(12);

        Node node21 = new Node(21);

        Node node22 = new Node(22);

        root.left = node1;

        root.right = node2;

        node1.left = node11;

        node1.right = node12;

        node2.left = node21;

        node2.right = node22;

        return root;

    }

    public static class Node {

        public Node left;

        public Node right;

        public int value;

        public Node(int value) {

            this.value = value;

        }

    }

}

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);

}

Gaibaota(N) = Gaibaota(N-1) + 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實現一個快速排序。

本人只研究過氣泡排序、選擇排序和快速排序,下面是快速排序的程式碼:

氣泡排序:

private static void bubbleSort(int[] array) {

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

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

            if (array[i] < array[j]) {

                int temp = array[i];

                array[i] = array[j];

                array[j] = temp;

            }

        }

    }

}

快速排序:

public class QuickSort {

    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);

        }

    }

    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程式碼將陣列元素順序顛倒

public class AnswerB11 {

    public static void main(String[] args) {

        int[] array = { 2, 25, 21, 63, 234, 83 };

        reverse(array);

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

    }

    private static void reverse(int[] array) {

        for (int i = 0; i < array.length / 2; i++) {

            int temp = array[i];

            array[i] = array[array.length - 1 - i];

            array[array.length - 1 - i] = temp;

        }

    }

}

import java.util.Stack;

public class AnswerB13 {

    public static void main(String[] args) {

        Node tree = makeupTree();

        Stack<Node> stack = new Stack<Node>();

        Node currentNode = tree;

        while (currentNode != null) {

            System.out.println(currentNode.value);

            stack.push(currentNode);

            currentNode = currentNode.left;

            if (currentNode == null) {

                Node parent = stack.pop();

                currentNode = parent.right;

                if (currentNode == null) {

                   if (stack.isEmpty()) {

                       break;

                   }

                   Node parentParent = stack.pop();

                   currentNode = parentParent.right;

                }

            }

        }

    }

    private static Node makeupTree() {

        Node root = new Node(0);

        Node node1 = new Node(1);

        Node node2 = new Node(2);

        Node node11 = new Node(11);

        Node node12 = new Node(12);

        Node node21 = new Node(21);

        Node node22 = new Node(22);

        root.left = node1;

        root.right = node2;

        node1.left = node11;

        node1.right = node12;

        node2.left = node21;

        node2.right = node22;

        return root;

    }

    public static class Node {

        public Node left;

        public Node right;

        public int value;

        public Node(int value) {

            this.value = value;

        }

    }

}