airbnb面試題

1.打印如下分形圖:

輸入1:
  O
O   O
輸入2:
      O
    O   O
  O       O
O   O   O   O

代碼:

Character[][] map;
    public void draw(int n) {
        int m = (int)Math.pow(2, n);
        map = new Character[m][2 * m - 1];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < map[0].length; j++) {
                map[i][j] = '\0';
            }
        }
        print(n, 0, 0);
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < map[0].length; j++) {
                System.out.print(map[i][j]);
            }
            System.out.println();
        }
    }
    private void print(int n, int x, int y) {
        if (n == 0) {
            map[x][y] = 'O';
            return;
        }
        int m = (int)Math.pow(2, n - 1);
        print(n - 1, x, y + m);
        print(n - 1, x + m, y);
        print(n - 1, x + m, y + m * 2);
    }

2.Pour Water

We are given an elevation map, heights[i] representing the height of the terrain at that index. The width at each index is 1. After V units of water fall at index K , how much water is at each index?

Water first drops at index K and rests on top of the highest terrain or water at that index. Then, it flows according to the following rules:

If the droplet would eventually fall by moving left, then move left.
Otherwise, if the droplet would eventually fall by moving right, then move right.
Otherwise, rise at it’s current position.
Here, “eventually fall” means that the droplet will eventually be at a lower level if it moves in that direction. Also, “l(fā)evel” means the height of the terrain plus any water in that column.
We can assume there’s infinitely high terrain on the two sides out of bounds of the array. Also, there could not be partial water being spread out evenly on more than 1 grid block - each unit of water has to be in exactly one block.

Note:

heights will have length in [1, 100] and contain integers in [0, 99] .
V will be in range [0, 2000] .
K will be in range [0, heights.length - 1] .

private void pour(int[] heights, int v, int p) {
        int[] waters = new int[heights.length];
        while(v-- > 0) {
            int cur = p;
            int pos = -1;
            while(cur > 0 && heights[cur - 1] + waters[cur - 1] <= heights[cur] + waters[cur]) {
                if (heights[cur - 1] + waters[cur - 1] < heights[cur] + waters[cur]) {
                    pos = cur - 1;
                }
                cur--;
            }
            cur = p;
            while(pos == -1 && cur < heights.length - 1 && heights[cur + 1] + waters[cur + 1] <= heights[cur] + waters[cur]) {
                if (heights[cur + 1] + waters[cur + 1] < heights[cur] + waters[cur]) {
                    pos = cur + 1;
                }
                cur++;
            }
            pos = pos == -1 ? p : pos;
            waters[pos]++;
        }
        //print
        int max = heights[0];
        for (int h : heights) {
            if (h > max) {
                max = h;
            }
        }
        for (int i = max; i > 0; i--) {
            for (int j = 0; j < heights.length; j++) {
                if (heights[j] + waters[j] < i) {
                    System.out.printf(" ");
                } else if (heights[j] < i) {
                    System.out.printf("W");
                } else {
                    System.out.printf("#");
                }
            }
            System.out.println();
        }
    }

3.Sliding Puzzle

On a 2x3 board , there are 5 tiles represented by the integers 1 through 5, and an empty square represented by 0.

A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.

The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].

Given a puzzle board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.

Note:

heights will have length in [1, 100] and contain integers in [0, 99] .
V will be in range [0, 2000] .
K will be in range [0, heights.length - 1] .

bfs

public int slidePuzzle(int[][] board) {
        String from = "";
        for (int[] row : board) {
            for (int k : row) {
                from += k;
            }
        }
        String to = "123450";
        int[][] next = new int[][]{{1, 3}, {0, 2, 4}, {1, 5}, {0, 4}, {1, 3, 5}, {2, 4}};
        Queue<String> q = new LinkedList<>();
        Set<String> used = new HashSet<>();
        q.offer(from);
        used.add(from);
        int steps = 0;
        while (!q.isEmpty()) {
            int n = q.size();
            while (n-- > 0) {
                String cur = q.poll();
                if (cur.equals(to)) {
                    return steps;
                }
                int ind = cur.indexOf("0");
                for (int move : next[ind]) {
                    char[] chars = cur.toCharArray();
                    char tmp = chars[move];
                    chars[move] = '0';
                    chars[ind] = tmp;
                    String s = String.valueOf(chars);
                    if (!used.contains(s)) {
                        used.add(s);
                        q.add(s);
                    }
                }
            }
            steps++;
        }
        return -1;
    }

4.Alien Dictionary

There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.

Example 1:

Input:
[
"wrt",
"wrf",
"er",
"ett",
"rftt"
]

Output: "wertf"
Example 2:

Input:
[
"z",
"x"
]

Output: "zx"
Example 3:

Input:
[
"z",
"x",
"z"
]

Output: ""

Explanation: The order is invalid, so return "".
Note:

You may assume all letters are in lowercase.
You may assume that if a is a prefix of b, then a must appear before b in the given dictionary.
If the order is invalid, return an empty string.
There may be multiple valid order of letters, return any one of them is fine.

入度為0的點(diǎn),說(shuō)明沒(méi)有前置節(jié)點(diǎn)讲仰,可以加入輸出慕趴。

public String alienOrder(String[] words) {
        Map<Character, Set<Character>> graph = constructGraph(words);
        Map<Character, Integer> inDegreeSet = getInDegree(graph);
        String result = "";
        Queue<Character> q = new LinkedList<>();
        for (Character c : inDegreeSet.keySet()) {
            if (inDegreeSet.get(c) == 0) {
                q.offer(c);
            }
        }
        while (!q.isEmpty()) {
            Character c = q.poll();
            result += c;
            for (Character neighbour : graph.get(c)) {
                inDegreeSet.put(neighbour, inDegreeSet.get(neighbour) - 1);
                if (inDegreeSet.get(neighbour) == 0) {
                    q.offer(neighbour);
                }
            }
        }
        if (result.length() != graph.keySet().size()) {
            return "";
        }
        return result;
    }

    private Map<Character, Integer> getInDegree(Map<Character, Set<Character>> graph) {
        Map<Character, Integer> inDegreeMap = new HashMap<>();
        for (Character key : graph.keySet()) {
            inDegreeMap.put(key, 0);
        }
        for (Character key : graph.keySet()) {
            for (Character c : graph.get(key)) {
                inDegreeMap.put(c, inDegreeMap.get(c) + 1);
            }
        }
        return inDegreeMap;
    }

    private Map<Character, Set<Character>> constructGraph(String[] words) {
        Map<Character, Set<Character>> graph = new HashMap<>();
        for (String word : words) {
            for (Character c : word.toCharArray()) {
                if (!graph.containsKey(c)) {
                    graph.put(c, new HashSet<>());
                }
            }
        }
        for (int i = 0; i < words.length - 1; i++) {
            int ind = 0;
            while (ind < words[i].length() && ind < words[i + 1].length()) {
                if (words[i].charAt(ind) != words[i + 1].charAt(ind)) {
                    graph.get(words[i].charAt(ind)).add(words[i + 1].charAt(ind));
                    break;
                }
                ind++;
            }
        }
        return graph;
    }

5.Palindrome Pairs

Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.

Example 1:

Input: ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]]
Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]
Example 2:

Input: ["bat","tab","cat"]
Output: [[0,1],[1,0]]
Explanation: The palindromes are ["battab","tabbat"]

public List<List<Integer>> palindromePairs(String[] words) {
        List<List<Integer>> result = new ArrayList<>();
        Map<String, Integer> m = new HashMap<>();
        for (int i = 0; i < words.length; i++) {
            m.put(words[i], i);
        }
        for (int i = 0; i < words.length; i++) {
            for (int j = 0; j <= words[i].length(); j++) {
                String s1 = words[i].substring(0, j);
                String s2 = words[i].substring(j);
                if (isPalind(s1)) {
                    String re = new StringBuffer(s2).reverse().toString();
                    if (m.containsKey(re) && m.get(re) != i) {
                        List<Integer> tmp = new ArrayList<>();
                        tmp.add(m.get(re));
                        tmp.add(i);
                        result.add(tmp);
                    }
                }
                if (isPalind(s2)) {
                    String re = new StringBuffer(s1).reverse().toString();
                    if (m.containsKey(re) && m.get(re) != i && s2.length() != 0) {
                        List<Integer> tmp = new ArrayList<>();
                        tmp.add(i);
                        tmp.add(m.get(re));
                        result.add(tmp);
                    }
                }
            }
        }
        return result;
    }
    private boolean isPalind(String word) {
        int a = 0;
        int b = word.length() - 1;
        while (a < b) {
            if (word.charAt(a) != word.charAt(b)) {
                return false;
            }
            a++;
            b--;
        }
        return true;
    }

6.Flatten 2D Vector

Implement an iterator to flatten a 2d vector.

For example,
Given 2d vector =
[
[1,2],
[3],
[4,5,6]
]

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,2,3,4,5,6].

Hint:

  1. How many variables do you need to keep track?
  2. Two variables is all you need. Try with x and y.
  3. Beware of empty rows. It could be the first few rows.
  4. To write correct code, think about the invariant to maintain. What is it?
  5. The invariant is x and y must always point to a valid point in the 2d vector. Should you maintain your invariant ahead of time or right when you need it?
  6. Not sure? Think about how you would implement hasNext(). Which is more complex?
  7. Common logic in two different places should be refactored into a common method.

Follow up:
As an added challenge, try to code it using only iterators in C++ or iterators in Java.

public class Vector2D implements Iterator<Integer> {
    int indexList, indexElement; 
    List<List<Integer>> list;
    public Vector2D(List<List<Integer>> vec2d) {
        indexList = 0;
        indexElement = 0;
        list = vec2d;
    }
    @Override
    public Integer next() {
        return list.get(indexList).get(indexElement++); 
    }
    @Override
    public boolean hasNext() {
        while(indexList<list.size()) { 
            if(indexElement<list.get(indexList).size()){ 
                return true;
            } else {
                indexList++;
                indexElement = 0;
            }
        }
        return false;
    }
}

7.menu order

類似于Combination Sum II
給定每個(gè)菜的價(jià)格,可用的總金額。

List<List<Integer>> result;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        result = new ArrayList<>();
        combine(candidates, 0, candidates.length - 1, target, new ArrayList<>());
        return result;
    }
    private void combine(int[] candidates, int l, int r, int target, List<Integer> last) {
        int pre = -1;
        for (int i = l; i <= r; i++) {
            if (candidates[i] == pre) {
                continue;
            }
            pre = candidates[i];
            if (candidates[i] == target) {
                List<Integer> tmp = new ArrayList<>(last);
                tmp.add(candidates[i]);
                result.add(tmp);
            } else if (candidates[i] < target) {
                last.add(candidates[i]);
                combine(candidates, i + 1, r, target - candidates[i], last);
                last.remove(last.size() - 1);
            }
        }
    }

8.flight ticket list

每一項(xiàng)包括departure, arrival, cost冕房,然后給一個(gè)整數(shù)k, 表示最多允許k次中轉(zhuǎn)躏啰。給定起始地點(diǎn)A,到達(dá)地點(diǎn)B, 要求輸出從A到B的最小花費(fèi)耙册,最多k次中轉(zhuǎn)给僵。

public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
        Map<Integer, Map<Integer, Integer>> m = new HashMap<>();
        for (int i = 0; i < flights.length; i++) {
            if (!m.containsKey(flights[i][0])) {
                m.put(flights[i][0], new HashMap<>());
            }
            m.get(flights[i][0]).put(flights[i][1], flights[i][2]);
        }
        Queue<int[]> q = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
        q.add(new int[]{0, src, K + 1});
        while (!q.isEmpty()) {
            int[] tmp = q.remove();
            if (tmp[1] == dst) {
                return tmp[0];
            }
            if (tmp[2] == 0) {
                continue;
            }
            Map<Integer, Integer> edges = m.getOrDefault(tmp[1], new HashMap<>());
            for (int city : edges.keySet()) {
                q.add(new int[]{tmp[0] + edges.get(city), city, tmp[2] - 1});
            }
        }
        return -1;
    }

9.數(shù)轉(zhuǎn)換步數(shù)計(jì)算

輸入兩棵樹A,B详拙,B是A經(jīng)過(guò)如下操作后得到的:
改變A中某節(jié)點(diǎn)的符號(hào)帝际,并改變它的孫子,孫子的孫子的符號(hào)饶辙;
問(wèn)胡本,需要對(duì)幾個(gè)節(jié)點(diǎn)進(jìn)行上述操作。

public int countSteps(TreeNode a, TreeNode b) {
        return count(a, b, new boolean[2]);
    }

    public int count(TreeNode a, TreeNode b, boolean[] flag) {
        if (a == null) {
            return 0;
        }
        boolean[] f = new boolean[2];
        a.val = flag[0] ? -a.val : a.val;
        f[0] = flag[1];
        int cnt = 0;
        if (a.val != b.val) {
            f[1] = true;
            cnt++;
        }
        return count(a.left, b.left, f) + count(a.right, b.right, f) + cnt;
    }

9. string multiply

字符串相乘畸悬,可能有負(fù)數(shù)

public String multiply(String a, String b) {
        boolean flag = true;
        if (a.charAt(0) == '+' || a.charAt(0) == '-') {
            flag = a.charAt(0) == '-' ? false : true;
            a = a.substring(1);
        }
        if (b.charAt(0) == '+' || b.charAt(0) == '-') {
            flag = b.charAt(0) == '-' ? !flag : flag;
            b = b.substring(1);
        }
        int[] x = new int[a.length()];
        int[] y = new int[b.length()];
        for (int i = 0; i < a.length(); i++) {
            x[i] = a.charAt(a.length() - i - 1) - '0';
        }
        for (int i = 0; i < b.length(); i++) {
            y[i] = b.charAt(b.length() - i - 1) - '0';
        }
        int[] res = new int[a.length() + b.length()];
        for (int i = 0; i < x.length; i++) {
            for (int j = 0; j < y.length; j++) {
                res[i + j] += x[i] * y[j];
                res[i + j + 1] += res[i + j] / 10;
                res[i + j] = res[i + j] % 10;
            }
        }
        String s = "";
        int ind = res.length - 1;
        while (ind >= 0 && res[ind] == 0) {
            ind--;
        }
        for (int i = ind; i >= 0; i--) {
            s += res[i];
        }
        String result = (ind == -1) ? "0" : s;
        return result == "0" ? "0" : flag ? s : "-" + s;
    }

10.Pyramid Transition Matrix

public boolean pyramidTransition(String bottom, List<String> allowed) {
        Map<String, Set<String>> m = new HashMap<>();
        for (String s : allowed) {
            if (!m.containsKey(s.substring(0, 2))) {
                m.put(s.substring(0, 2), new HashSet<>());
            }
            m.get(s.substring(0, 2)).add(s.substring(2));
        }
        return dfs(bottom, m, 0, "");
    }

    private boolean dfs(String bottom, Map<String, Set<String>> m, int i, String next) {
        if (bottom.length() == 1) {
            return true;
        }
        if (i == bottom.length() - 1) {
            return dfs(next, m, 0, "");
        }

        if (m.containsKey(bottom.substring(i, i + 2))) {
            for (String s : m.get(bottom.substring(i, i + 2))) {
                if (dfs(bottom, m, i + 1, next + s)) {
                    return true;
                }
            }
        }
        return false;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末侧甫,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子蹋宦,更是在濱河造成了極大的恐慌披粟,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,734評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件冷冗,死亡現(xiàn)場(chǎng)離奇詭異守屉,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)蒿辙,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門拇泛,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人思灌,你說(shuō)我怎么就攤上這事俺叭。” “怎么了泰偿?”我有些...
    開封第一講書人閱讀 164,133評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵熄守,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我耗跛,道長(zhǎng)裕照,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,532評(píng)論 1 293
  • 正文 為了忘掉前任调塌,我火速辦了婚禮晋南,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘羔砾。我一直安慰自己负间,他們只是感情好偶妖,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,585評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著唉擂,像睡著了一般餐屎。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上玩祟,一...
    開封第一講書人閱讀 51,462評(píng)論 1 302
  • 那天腹缩,我揣著相機(jī)與錄音,去河邊找鬼空扎。 笑死藏鹊,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的转锈。 我是一名探鬼主播盘寡,決...
    沈念sama閱讀 40,262評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼撮慨!你這毒婦竟也來(lái)了竿痰?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,153評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤砌溺,失蹤者是張志新(化名)和其女友劉穎影涉,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體规伐,經(jīng)...
    沈念sama閱讀 45,587評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡蟹倾,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,792評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了猖闪。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片鲜棠。...
    茶點(diǎn)故事閱讀 39,919評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖培慌,靈堂內(nèi)的尸體忽然破棺而出豁陆,到底是詐尸還是另有隱情,我是刑警寧澤检柬,帶...
    沈念sama閱讀 35,635評(píng)論 5 345
  • 正文 年R本政府宣布献联,位于F島的核電站,受9級(jí)特大地震影響何址,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜进胯,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,237評(píng)論 3 329
  • 文/蒙蒙 一用爪、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧胁镐,春花似錦偎血、人聲如沸诸衔。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)笨农。三九已至,卻和暖如春帖渠,著一層夾襖步出監(jiān)牢的瞬間谒亦,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工空郊, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留份招,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,048評(píng)論 3 370
  • 正文 我出身青樓狞甚,卻偏偏與公主長(zhǎng)得像锁摔,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子哼审,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,864評(píng)論 2 354

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

  • Swift1> Swift和OC的區(qū)別1.1> Swift沒(méi)有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對(duì)...
    cosWriter閱讀 11,101評(píng)論 1 32
  • 在iOS 4.2和以后谐腰,應(yīng)用程序可以添加對(duì)本地打印機(jī)的打印內(nèi)容的支持。盡管并非所有應(yīng)用程序都需要打印支持涩盾,但是如果...
    陵無(wú)山閱讀 3,619評(píng)論 0 4
  • 劉娜 焦點(diǎn)解決網(wǎng)絡(luò)初級(jí)九期 駐馬店 2018~03~28 堅(jiān)持分享第32天 學(xué)校的家長(zhǎng)志愿者校門口值班輪...
    洋帆起航閱讀 164評(píng)論 0 0
  • 你是我的boy閱讀 182評(píng)論 0 0
  • 今天的天空很藍(lán)十气,大廈很高,心情復(fù)雜旁赊。是不是剛出大學(xué)都會(huì)面對(duì)這樣同一個(gè)問(wèn)題:外面的世界很精彩桦踊,很隨意,但卻很現(xiàn)實(shí)...
    萌萌小女子閱讀 127評(píng)論 0 0