蚂蚁笔试

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 1.实现两个线程,使之交替打印1-100,
 * 如:两个线程分别为:Printer1和Printer2,
 * 最后输出结果为: Printer1 — 1 Printer2 一 2 Printer1 一 3 Printer2 一 4
 * @date 2019-03-07
 * @mondify
 * @copyright
 */
public class Test {
    private int number = 1;

    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();

    public void loopA() {
        lock.lock();

        try {
            if (number % 2 == 0) {
                condition1.await();
            }

            System.out.println(Thread.currentThread().getName() + "-" + number + " ");

            number++;
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void loopB() {
        lock.lock();

        try {
            if (number % 2 != 0) {
                condition2.await();
            }

            System.out.println(Thread.currentThread().getName() + "-" + number + " ");

            number++;
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        Test ad = new Test();

        new Thread(() -> {

            for (int i = 1; i <= 50; i++) {
                ad.loopA();
            }

        }, "Printer1").start();

        new Thread(() -> {

            for (int i = 1; i <= 50; i++) {
                ad.loopB();
            }

        }, "Printer2").start();

    }

}
package com.ksyun;

/**
 * 2.实现函数,给定一个字符串数组,求该数组的连续非空子集,分別打印出来各子集
 * 举例数组为[abc],输出[a],[b],[c],[ab],[bc],[abc]
 *
 * @author xubh
 * @date 2019-03-07
 * @mondify
 * @copyright
 */
public class Test2 {

    public static void main(String[] args) {
        String s = "abc";
        char[] in = s.toCharArray();

        print(in, new StringBuilder(), 0);
        System.out.println();
        print2(s, new StringBuilder());

    }


    public static void print(char[] in, StringBuilder sb, int start) {
        int len = in.length;
        for (int i = start; i < len; i++) {
            sb.append(in[i]);
            System.out.print("[" + sb + "],");
            if (i < len - 1) {
                print(in, sb, i + 1);
            }
            sb.setLength(sb.length() - 1);
        }
    }

    public static void print2(String str, StringBuilder sb) {
        for (int i = 0; i < str.length(); i++) {
            for (int j = i; j < str.length(); j++) {
                sb.append("[").append(str, i, j + 1).append("]").append(",");
            }
        }
        sb.setLength(sb.length() - 1);
        System.out.println(sb);
    }
}
package com.ksyun;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;

/**
 * 3.文件系统中按逗号分割保存了1亿个正整数(一行10个数,1000万行),找出其中最大的100个数
 *
 * @author xubh
 * @date 2019-03-08
 * @mondify
 * @copyright
 */
public class Test3 {
    /**
     * 用PriorityQueue默认是自然顺序排序,要选择最大的k个数,构造小顶堆,
     * 每次取数组中剩余数与堆顶的元素进行比较,如果新数比堆顶元素大,则删除堆顶元素,并添加这个新数到堆中。
     */
    public static void main(String[] args) {
        System.out.println(getTopK("C:\\Users\\Administrator\\Desktop\\note\\TopKTest.txt", 6));
    }

    public static List<Integer> getTopK(String filePath, int k) {
        List<Integer> list = new ArrayList<>();
        Queue<Integer> queue = new PriorityQueue<>(k);
        File file = new File(filePath);
        BufferedReader reader;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tmp;
            while ((tmp = reader.readLine()) != null) {
                String[] strings = tmp.split(",");
                for (String str : strings) {
                    int num = Integer.parseInt(str);
                    if (queue.size() < k) {
                        queue.offer(num);
                    } else if (queue.peek() < num) {
                        queue.poll();
                        queue.offer(num);
                    }
                }
            }
            while (k-- > 0) {
                list.add(queue.poll());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 启动3个线程打印递增的数字, 线程1先打印1,2,3,4,5,
 * 然后是线程2打印6,7,8,9,10, 然后是线程3打印11,12,13,14,15.
 * 接着再由线程1打印16,17,18,19,20….以此类推, 直到打印到75
 *
 * @author xubh
 * @date 2019-03-19
 * @mondify
 * @copyright
 */
public class Test4 {
    private int no = 1;
    private final Lock lock = new ReentrantLock();
    private final Condition con1 = lock.newCondition();
    private final Condition con2 = lock.newCondition();
    private final Condition con3 = lock.newCondition();
    private int curNum = 1;

    private void printNum() {
        if (curNum > 75) {
            Thread.currentThread().interrupt();
            return;
        }
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + "  " + (curNum++));
        }
    }

    public void process1() {
        lock.lock();
        try {
            while (no != 1) {
                con1.await();
            }
            printNum();
            no = 2;
            con2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void process2() {
        lock.lock();
        try {
            while (no != 2) {
                con2.await();
            }
            printNum();
            no = 3;
            con3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void process3() {
        lock.lock();
        try {
            while (no != 3) {
                con3.await();
            }
            printNum();
            no = 1;
            con1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        Test4 p = new Test4();
        new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                p.process1();
            }
        }, "A").start();

        new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                p.process2();
            }
        }, "B").start();

        new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                p.process3();
            }
        }, "C").start();

    }
}
import java.util.concurrent.Semaphore;

/**
 * 启动3个线程打印递增的数字, 线程1先打印1,2,3,4,5,
 * 然后是线程2打印6,7,8,9,10, 然后是线程3打印11,12,13,14,15.
 * 接着再由线程1打印16,17,18,19,20….以此类推, 直到打印到75
 *
 * @author xubh
 * @date 2019-03-19
 * @mondify
 * @copyright
 */
public class Test4 {
    /**
     * 以A开始的信号量,初始信号量数量为1
     */
    private static Semaphore A = new Semaphore(1);
    /**
     * B、C信号量,A完成后开始,初始信号数量为0
     */
    private static Semaphore B = new Semaphore(0);
    private static Semaphore C = new Semaphore(0);

    private int curNum = 1;

    private void printNum() {
        if (curNum > 75) {
            Thread.currentThread().interrupt();
            return;
        }
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + "  " + (curNum++));
        }
    }


    public void process1() {
        try {
            // A获取信号执行,A信号量减1,当A为0时将无法继续获得该信号量
            A.acquire();
            printNum();
            // B释放信号,B信号量加1(初始为0),此时可以获取B信号量
            B.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void process2() {
        try {
            B.acquire();
            printNum();
            C.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void process3() {
        try {
            C.acquire();
            printNum();
            A.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        Test4 p = new Test4();
        new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                p.process1();
            }
        }, "A").start();

        new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                p.process2();
            }
        }, "B").start();

        new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                p.process3();
            }
        }, "C").start();

    }
}
import java.util.HashMap;
import java.util.Map;

/**
 * 打印一个数组中和为K的连续子数组
 *
 * @author xubh
 * @date 2019-03-19
 * @mondify
 * @copyright
 */
public class Test4 {

    /**
     * 用一个哈希表来建立连续子数组之和跟其出现次数之间的映射,初始化要加入{0,1}这对映射,
     * 我们建立哈希表的目的是为了让我们可以快速的查找sum-k是否存在,即是否有连续子数组的和为sum-k,
     * 如果存在的话,那么和为k的子数组一定也存在,这样当sum刚好为k的时候,那么数组从起始到当前位置的这段子数组的和就是k,
     * 满足题意,如果哈希表中事先没有m[0]项的话,这个符合题意的结果就无法累加到结果res中,这就是初始化的用途。
     */
    public static int subarraySum(int[] nums, int k) {

        int sum = 0;
        int res = 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, 1);

        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            if (map.containsKey(sum - k)) {
                res += map.get(sum - k);
            }
            map.put(sum, map.getOrDefault(sum, 0) + 1);
        }
        return res;
    }

    public static int subarraySum2(int[] nums, int k) {
        int n = nums.length;
        int res = 0;
        int[] sum = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            sum[i] = sum[i - 1] + nums[i - 1];
        }
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                if (sum[j + 1] - sum[i] == k) {
                    res++;
                }
            }
        }
        return res;
    }


    public static void main(String[] args) {
        int[] nums = {1, 1, 3, 4, 1};
        int k = 5;
        int res = subarraySum2(nums, k);
        System.out.println(res);
    }

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

推荐阅读更多精彩内容