蚂蚁笔试

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

}

推荐阅读更多精彩内容