想学习算法?Java笔试手写算法面试12题『含答案』整的明明白白

前言:

我坚信,机会永远属于有准备的人,我们与其羡慕他人的成功,不如从此刻起,积累足够多的的知识和面试经验,为将来进入更好的工作做好充分的准备!

算法面试题+答案

1. 统计一篇英文文章单词个数。

public class WordCounting {
    public static void main(String[] args) {
        try(FileReader fr = new FileReader("a.txt")) {
            int counter = 0;
            Boolean state = false;
            int currentchar;
            while((currentchar= fr.read()) != -1) {
                if(currentchar== ' ' || currentchar == 'n'|| currentchar == 't' || currentchar == 'r') {
                    state = false;
                } else if(!state) {
                    state = true;
                    counter++;
                }
            }
            System.out.println(counter);
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}

补充:这个程序可能有很多种写法,这里选择的是Dennis M. Ritchie和Brian W. Kernighan老师在他们不朽的著作《The C Programming Language》中给出的代码,向两位老师致敬。下面的代码也是如此。

2. 输入年月日,计算该日期是这一年的第几天。

public class DayCounting {
    public static void main(String[] args) {
        int[][] data = {
        {31,28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
        {31,29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
        };
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入年月日(1980 11 28): ");
        int year = sc.nextint();
        int month = sc.nextint();
        int date = sc.nextint();
        int[] daysOfMonth = data[(year % 4 == 0 && year % 100 != 0 || year % 400 == 0)?1 : 0];
        int sum = 0;
        for (int i = 0; i < month -1; i++) {
            sum += daysOfMonth[i];
        }
        sum += date;
        System.out.println(sum);
        sc.close();
    }
}

3. 回文素数:所谓回文数就是顺着读和倒着读一样的数(例如:11,121,1991…),回文素数就是既是回文数又是素数(只能被1和自身整除的数)的数。编程找出11~9999之间的回文素数。

public class PalindromicPrimeNumber {
    public static void main(String[] args) {
        for (int i = 11; i <= 9999; i++) {
            if(isPrime(i) && isPalindromic(i)) {
                System.out.println(i);
            }
        }
    }
    public static Boolean isPrime(int n) {
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if(n % i == 0) {
                return false;
            }
        }
        return true;
    }
    public static Boolean isPalindromic(int n) {
        int temp = n;
        int sum = 0;
        while(temp > 0) {
            sum= sum * 10 + temp % 10;
            temp/= 10;
        }
        return sum == n;
    }
}

4. 全排列:给出五个数字12345的所有排列。

public class FullPermutation {
    public static void perm(int[] list) {
        perm(list,0);
    }
    private static void perm(int[] list, int k) {
        if (k == list.length) {
            for (int i = 0; i < list.length; i++) {
                System.out.print(list[i]);
            }
            System.out.println();
        } else{
            for (int i = k; i < list.length; i++) {
                swap(list, k, i);
                perm(list, k + 1);
                swap(list, k, i);
            }
        }
    }
    private static void swap(int[] list, int pos1, int pos2) {
        int temp = list[pos1];
        list[pos1] = list[pos2];
        list[pos2] = temp;
    }
    public static void main(String[] args) {
        int[] x = {1, 2, 3, 4, 5};
        perm(x);
    }
}

5. 对于一个有N个整数元素的一维数组,找出它的子数组(数组中下标连续的元素组成的数组)之和的最大值。

下面给出几个例子(最大子数组用粗体表示):

  • 数组:{ 1, -2, 3,5, -3, 2 },结果是:8
  • 数组:{ 0, -2, 3, 5, -1, 2 },结果是:9
  • 数组:{ -9, -2,-3, -5, -3 },结果是:-2

可以使用动态规划的思想求解:

public class MaxSum {
    private static int max(int x, int y) {
        return x > y? x: y;
    }
    public static int maxSum(int[] array) {
        int n = array.length;
        int[] start = new int[n];
        int[] all = new int[n];
        all[n - 1] = start[n - 1] = array[n - 1];
        for (int i = n - 2; i >= 0;i--) {
            start[i] = max(array[i], array[i] + start[i + 1]);
            all[i] = max(start[i], all[i + 1]);
        }
        return all[0];
    }
    public static void main(String[] args) {
        int[] x1 = { 1, -2, 3, 5,-3, 2 };
        int[] x2 = { 0, -2, 3, 5,-1, 2 };
        int[] x3 = { -9, -2, -3,-5, -3 };
        System.out.println(maxSum(x1));
        // 8
        System.out.println(maxSum(x2));
        // 9
        System.out.println(maxSum(x3));
        //-2
    }
}

6. 用递归实现字符串倒转

public class StringReverse {
    public static String reverse(String originStr) {
        if(originStr == null || originStr.length()== 1) {
            return originStr;
        }
        return reverse(originStr.substring(1))+ originStr.charAt(0);
    }
    public static void main(String[] args) {
        System.out.println(reverse("hello"));
    }
}

7. 输入一个正整数,将其分解为素数的乘积。

public class DecomposeInteger {
    private static List<Integer> list = new ArrayList<Integer>();
    public static void main(String[] args) {
        System.out.print("请输入一个数: ");
        Scanner sc = new Scanner(System.in);
        int n = sc.nextint();
        decomposeNumber(n);
        System.out.print(n + " = ");
        for (int i = 0; i < list.size() - 1; i++) {
            System.out.print(list.get(i) + " * ");
        }
        System.out.println(list.get(list.size() - 1));
    }
    public static void decomposeNumber(int n) {
        if(isPrime(n)) {
            list.add(n);
            list.add(1);
        } else {
            doIt(n, (int)Math.sqrt(n));
        }
    }
    public static void doIt(int n, int div) {
        if(isPrime(div) && n % div == 0) {
            list.add(div);
            decomposeNumber(n / div);
        } else {
            doIt(n, div - 1);
        }
    }
    public static Boolean isPrime(int n) {
        for (int i = 2; i <= Math.sqrt(n);i++) {
            if(n % i == 0) {
                return false;
            }
        }
        return true;
    }
}

8. 一个有n级的台阶,一次可以走1级、2级或3级,问走完n级台阶有多少种走法。

public class GoSteps {
    public static int countWays(int n) {
        if(n < 0) {
            return 0;
        } else if(n == 0) {
            return 1;
        } else {
            return countWays(n - 1) + countWays(n - 2) + countWays(n -3);
        }
    }
    public static void main(String[] args) {
        System.out.println(countWays(5));
        // 13
    }
}

9. 写一个算法判断一个英文单词的所有字母是否全都不同(不区分大小写)

public class AllNotTheSame {
    public static Boolean judge(String str) {
        String temp = str.toLowerCase();
        int[] letterCounter = new int[26];
        for (int i = 0; i <temp.length(); i++) {
            int index = temp.charAt(i)- 'a';
            letterCounter[index]++;
            if(letterCounter[index] > 1) {
                return false;
            }
        }
        return true;
    }
    public static void main(String[] args) {
        System.out.println(judge("hello"));
        System.out.print(judge("smile"));
    }
}

10. 有一个已经排好序的整数数组,其中存在重复元素,请将重复元素删除掉,例如,A= [1, 1, 2, 2, 3],处理之后的数组应当为A= [1, 2, 3]。

public class RemoveDuplication {
    public static int[] removeDuplicates(int a[]) {
        if(a.length <= 1) {
            return a;
        }
        int index = 0;
        for (int i = 1; i < a.length; i++) {
            if(a[index] != a[i]) {
                a[++index] = a[i];
            }
        }
        int[] b = new int[index + 1];
        System.arraycopy(a, 0, b, 0, b.length);
        return b;
    }
    public static void main(String[] args) {
        int[] a = {1, 1, 2, 2, 3};
        a = removeDuplicates(a);
        System.out.println(Arrays.toString(a));
    }
}

11. 给一个数组,其中有一个重复元素占半数以上,找出这个元素。

public class FindMost {
    public static <T> T find(T[] x){
        T temp = null;
        for (int i = 0, nTimes = 0; i< x.length;i++) {
            if(nTimes == 0) {
                temp= x[i];
                nTimes= 1;
            } else {
                if(x[i].equals(temp)) {
                    nTimes++;
                } else {
                    nTimes--;
                }
            }
        }
        return temp;
    }
    public static void main(String[] args) {
        String[]strs = {"hello","kiss","hello","hello","maybe"};
        System.out.println(find(strs));
    }
}

12. 编写一个方法求一个字符串的字节长度?

public int getWordCount(String s){
    int length = 0;
    for (int i = 0; i < s.length(); i++)
    {
        int ascii = Character.codePointAt(s, i);
        if(ascii >= 0 && ascii <=255)
        length++; else
        length += 2;
    }
    return length;
}

写在最后:

想进大厂,光会算法可不行哟,像Kafka、Mysql、Tomcat、Docker、Spring、MyBatis、Nginx、Netty、Dubbo、Redis、Netty、Spring cloud、分布式、高并发、性能调优、微服务等架构技术都要掌握!

针对以上技术点呢,笔者也收集了一些面试题(详情后面截图),现在免费分享给大家!点击下方传送门即可免费领取

传送门

笔者收集的部分面试题截图

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容