螞蟻筆試

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

/**
 * @author 1.實(shí)現(xiàn)兩個(gè)線程,使之交替打印1-100,
 * 如:兩個(gè)線程分別為:Printer1和Printer2,
 * 最后輸出結(jié)果為: 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.實(shí)現(xiàn)函數(shù),給定一個(gè)字符串?dāng)?shù)組,求該數(shù)組的連續(xù)非空子集赎懦,分別打印出來各子集
 * 舉例數(shù)組為[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.文件系統(tǒng)中按逗號(hào)分割保存了1億個(gè)正整數(shù)(一行10個(gè)數(shù)鸭巴,1000萬(wàn)行)终娃,找出其中最大的100個(gè)數(shù)
 *
 * @author xubh
 * @date 2019-03-08
 * @mondify
 * @copyright
 */
public class Test3 {
    /**
     * 用PriorityQueue默認(rèn)是自然順序排序内边,要選擇最大的k個(gè)數(shù)挠他,構(gòu)造小頂堆蔬墩,
     * 每次取數(shù)組中剩余數(shù)與堆頂?shù)脑剡M(jìn)行比較,如果新數(shù)比堆頂元素大佑淀,則刪除堆頂元素留美,并添加這個(gè)新數(shù)到堆中。
     */
    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;

/**
 * 啟動(dòng)3個(gè)線程打印遞增的數(shù)字, 線程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;

/**
 * 啟動(dòng)3個(gè)線程打印遞增的數(shù)字, 線程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開始的信號(hào)量,初始信號(hào)量數(shù)量為1
     */
    private static Semaphore A = new Semaphore(1);
    /**
     * B伸刃、C信號(hào)量,A完成后開始,初始信號(hào)數(shù)量為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獲取信號(hào)執(zhí)行,A信號(hào)量減1,當(dāng)A為0時(shí)將無(wú)法繼續(xù)獲得該信號(hào)量
            A.acquire();
            printNum();
            // B釋放信號(hào)谎砾,B信號(hào)量加1(初始為0),此時(shí)可以獲取B信號(hào)量
            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;

/**
 * 打印一個(gè)數(shù)組中和為K的連續(xù)子數(shù)組
 *
 * @author xubh
 * @date 2019-03-19
 * @mondify
 * @copyright
 */
public class Test4 {

    /**
     * 用一個(gè)哈希表來建立連續(xù)子數(shù)組之和跟其出現(xiàn)次數(shù)之間的映射奕枝,初始化要加入{0,1}這對(duì)映射棺榔,
     * 我們建立哈希表的目的是為了讓我們可以快速的查找sum-k是否存在,即是否有連續(xù)子數(shù)組的和為sum-k隘道,
     * 如果存在的話症歇,那么和為k的子數(shù)組一定也存在,這樣當(dāng)sum剛好為k的時(shí)候谭梗,那么數(shù)組從起始到當(dāng)前位置的這段子數(shù)組的和就是k忘晤,
     * 滿足題意,如果哈希表中事先沒有m[0]項(xiàng)的話激捏,這個(gè)符合題意的結(jié)果就無(wú)法累加到結(jié)果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);
    }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末远舅,一起剝皮案震驚了整個(gè)濱河市闰蛔,隨后出現(xiàn)的幾起案子痕钢,更是在濱河造成了極大的恐慌,老刑警劉巖序六,帶你破解...
    沈念sama閱讀 216,843評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件任连,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡例诀,警方通過查閱死者的電腦和手機(jī)随抠,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,538評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來繁涂,“玉大人拱她,你說我怎么就攤上這事∪幼铮” “怎么了秉沼?”我有些...
    開封第一講書人閱讀 163,187評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)矿酵。 經(jīng)常有香客問我氧猬,道長(zhǎng),這世上最難降的妖魔是什么坏瘩? 我笑而不...
    開封第一講書人閱讀 58,264評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮漠魏,結(jié)果婚禮上倔矾,老公的妹妹穿的比我還像新娘。我一直安慰自己柱锹,他們只是感情好哪自,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,289評(píng)論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著禁熏,像睡著了一般壤巷。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上瞧毙,一...
    開封第一講書人閱讀 51,231評(píng)論 1 299
  • 那天胧华,我揣著相機(jī)與錄音,去河邊找鬼宙彪。 笑死矩动,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的释漆。 我是一名探鬼主播悲没,決...
    沈念sama閱讀 40,116評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼男图!你這毒婦竟也來了示姿?” 一聲冷哼從身側(cè)響起甜橱,我...
    開封第一講書人閱讀 38,945評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎栈戳,沒想到半個(gè)月后岂傲,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,367評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡荧琼,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,581評(píng)論 2 333
  • 正文 我和宋清朗相戀三年譬胎,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片命锄。...
    茶點(diǎn)故事閱讀 39,754評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡堰乔,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出脐恩,到底是詐尸還是另有隱情镐侯,我是刑警寧澤,帶...
    沈念sama閱讀 35,458評(píng)論 5 344
  • 正文 年R本政府宣布驶冒,位于F島的核電站苟翻,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏骗污。R本人自食惡果不足惜崇猫,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,068評(píng)論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望需忿。 院中可真熱鬧诅炉,春花似錦、人聲如沸屋厘。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,692評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)汗洒。三九已至议纯,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間溢谤,已是汗流浹背瞻凤。 一陣腳步聲響...
    開封第一講書人閱讀 32,842評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留溯香,地道東北人鲫构。 一個(gè)月前我還...
    沈念sama閱讀 47,797評(píng)論 2 369
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像玫坛,于是被迫代替她去往敵國(guó)和親结笨。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,654評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容