软件工程师技术面试一面真题

20190807 BlackRock技术面试一面 SDE实习 远程 不限时间 

如无特殊说明,必须使用Java进行解答。

本人给出的答案是自己的回答,并不是最优解。欢迎博友讨论,并指出可以优化之处。

1. 倒序排列给定字符串中的字母和数字(省略其他),用“-”连接

2. 使用最少纸币/硬币找零问题 要求展现OOP (是规则的面额,所以直接贪心算法)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * Decide if a certain note/coin is needed for change.
 */

/**
 * all the coins and notes
 */
enum Money {
    Fifty_Pound(50, "Fifty Pounds"), Twenty_Pound(20, "Twenty Pounds"), Ten_Pound(10,"Ten Pounds"), 
  Five_Pound(5, "Five Pounds"), Two_Pound(2,"Two Pounds"), One_Pound(1, "One Pound"), 
  Fifty_Pence(0.5, "Fifty Pence"), Twenty_Pence(0.2, "Twenty Pence"), Ten_Pence(0.1, "Ten Pence"),
  Five_Pence(0.05, "Five Pence"), Two_Pence(0.02, "Two Pence"), One_Pence( 0.01, "One Pence");

    private double value;
    private String code;

    private Money(double value, String code) {
        this.value = value;
        this.code = code;
    }

    public double getValue() {
        return value;
    }

    public String getCode() {
        return code;
    }

}


public class test {
    /**
     * Iterate through each line of input.
     */
    public static void main(String[] args) throws IOException {
        InputStreamReader reader = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(reader);

        try {
            double purchasePrice = Double.parseDouble(in.readLine());
            double cash = Double.parseDouble(in.readLine());
            test.calculateChange(purchasePrice, cash);
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public static void calculateChange(double purchasePrice, double cash) {
        // Access your code here. Feel free to create other classes as required

        if (cash == purchasePrice) { // no change needed
            System.out.println("ZERO");
            return;
        }
        // not enough cash or negative number
        if (cash < purchasePrice || cash < 0 || purchasePrice < 0) {
            System.out.println("ERROR");
            return;
        }
        double change = cash - purchasePrice; // amount that should be given back to customers
        String output = ""; // output on the screen
        Money[] values = Money.values();
        for (Money money : values) {
            int amount = (int) (change / money.getValue());
            change -= amount * money.getValue();
            // solve accuracy problem of java compiler
            change = (double) (Math.round(change * 100)) / 100;
            if (amount != 0) {
                for (int i = 0; i < amount; i++) {
                    output += money.getCode() + ", ";
                }
            }
            if (change == 0) { // no need to search smaller denominations
                break;
            }
        }
        if (output != "" || output != ", ") {
            output = output.substring(0, output.length() - 2); // get rid of last ", "
        }
        System.out.println(output);
    }
}

3. 

编程挑战说明:可选Java,Python

Given a pattern as the first argument and a string of blobs split by | show the number of times the pattern is present in each blob and the total number of matches.

 

输入:

The input consists of the pattern ("bc" in the example) which is separated by a semicolon followed by a list of blobs ("bcdefbcbebc|abcdebcfgsdf|cbdbesfbcy|1bcdef23423bc32" in the example). Example input: bc;bcdefbcbebc|abcdebcfgsdf|cbdbesfbcy|1bcdef23423bc32

 

输出:

The output should consist of the number of occurrences of the pattern per blob (separated by |). Additionally, the final entry should be the summation of all the occurrences (also separated by |).

 

Example output: 3|2|1|2|8 where 'bc' was repeated 3 times, 2 times, 1 time, 2 times in the 4 blobs passed in. And 8 is the summation of all the occurrences (3+2+1+2 = 8)

 

4. 编程挑战说明:

We say a portfolio matches the benchmark when the number of shares of each asset in the portfolio matches the number of shares of each asset in the benchmark. Your question is to write a program that determines the transactions necessary to make a portfolio match a benchmark.

A portfolio is a collection of assets such as stocks and bonds. A portfolio could have 10 shares of Vodafone stock, 15 shares of Google stock and 15 shares of Microsoft bonds. A benchmark is also just a collection of assets. A benchmark could have 15 shares of Vodafone stock, 10 shares of Google stock and 15 shares of Microsoft bonds.

A transaction is when you “buy” or “sell” a particular asset of certain asset type (“stock” or “bond”). For instance, you can decide to buy 5 shares of Vodafone stock which, given the portfolio described above, would result in you having 15 shares of Vodafone stock. Correspondingly, you decide to sell 5 shares of Microsoft bonds, which would result in 10 shares of Microsoft bonds in the above portfolio.

Assumptions:

Shares are positive decimals

There will always be at least 1 asset present in the Portfolio and Benchmark

A particular asset can be bond, stock, or both. For example, 5 shares of Microsoft bonds and 10 shares of Microsoft stock can both be present in the portfolio/benchmark

The trades should be sorted in alphabetical order based on the names of the assets; if both bonds and stock are present for an asset, list bonds first

输入:

The first part of the input is the Portfolio holdings (in the format Name,AssetType,Shares where each asset is separated by '|' symbol)

The second part of the input is the Benchmark holdings (in the format Name,AssetType,Shares where each asset is separated by '|' symbol)

Example input: Vodafone,STOCK,10|Google,STOCK,15|Microsoft,BOND,15:Vodafone,STOCK,15|Google,STOCK,10|Microsoft,BOND,15

Note that the two parts are separated by the ':' symbol.

输出:

The output is a list of transactions (separated by new line) in the format TransactionType,Name,AssetType,Shares. Note that the TransactionType should only be BUY or SELL.

Example output: SELL,Google,STOCK,5 BUY,Vodafone,STOCK,5

测试案例

测试1

测试输入

Vodafone,STOCK,10|Google,STOCK,15|Microsoft,BOND,15:Vodafone,STOCK,15|Google,STOCK,10|Microsoft,BOND,15

预期输出

SELL,Google,STOCK,5

BUY,Vodafone,STOCK,5

测试2

测试输入

Vodafone,STOCK,10|Google,STOCK,15:Vodafone,STOCK,15|Vodafone,BOND,10|Google,STOCK,10

预期输出

SELL,Google,STOCK,5

BUY,Vodafone,BOND,10

BUY,Vodafone,STOCK,5 

测试3

测试输入

Amazon,STOCK,10|Kugo,BOND,100:

测试4

测试输入

:Kugo, STOCK, 50

测试5

测试输入

Amazon,STOCK,10: Amazon,STOCK,10

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;

class Asset implements Comparable<Asset> {
    String name;
    String type;
    int share;  // assume positive integer, can change to BigInt to address potential overflow

    public Asset() {}

    public Asset(String name, String type, int share) {
        this.name = name;
        this.type = type;
        this.share = share;
    }

    void setName(String name) {
        this.name = name;
    }

    void setType(String type) {
        this.type = type;
    }

    void setShare(int share) {
        this.share = share;
    }

    String getName() {
        return name;
    }

    String getType() {
        return type;
    }

    int getShare() {
        return share;
    }


    @Override
    public String toString() {
        return "name:" + name + " type:" + type + " share:" + share;
    }


    /**
     * compare the name of the asset
     */
    @Override
    public int compareTo(Asset other) {
        return this.getName().compareTo(other.getName());
    }
}


public class Main {
    static ArrayList<Asset> portStock = new ArrayList<>(); // stock in the portfolio
    static ArrayList<Asset> portBond = new ArrayList<>(); // bond in the portfolio
    static ArrayList<Asset> benchStock = new ArrayList<>(); // stock in the benchmark
    static ArrayList<Asset> benchBond = new ArrayList<>(); // bond in the benchmark
    static ArrayList<String> sellList = new ArrayList<>();
    static ArrayList<String> buyList = new ArrayList<>();

    /**
     * Iterate through each line of input.
     */
    public static void main(String[] args) throws IOException {
        InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8);
        BufferedReader in = new BufferedReader(reader);
        String line;
        while ((line = in.readLine()) != null) {
            Main.matchBenchmark(line);
            updateList();
        }
    }

    public static void updateList() {
        sellList = new ArrayList<>();
        buyList = new ArrayList<>();
        portStock = new ArrayList<>();
        portBond = new ArrayList<>();
        benchStock = new ArrayList<>();
        benchBond = new ArrayList<>();
    }

    /**
     * Check if the asset belongs to bond or stock
     * 
     * @param source
     * @param bond
     * @param stock
     */
    public static void checkAsset(String[] source, ArrayList<Asset> bond, ArrayList<Asset> stock) {
        for (String s : source) {
            String[] tmp = s.split(",");
            int share = Integer.parseInt(tmp[2].trim());
            Asset asset = new Asset(tmp[0].trim(), tmp[1].trim(), share);
            if (isBond(tmp[1])) {
                bond.add(asset);
            } else if (isStock(tmp[1])) {
                stock.add(asset);
            } else {
                throw new IllegalArgumentException();
            }
        }
    }

    /**
     * split the input String into portfolio and benchmark part
     * 
     * @param input
     */
    public static void splitPortBench(String input) {
        String[] portAndBench = input.split(":");
        String[] portfolio;
        String[] bench;
        if (!input.contains(":")) { // invalid input
            return;

        }
        // normal case where both portfolio and benchmark have assets
        else if (portAndBench.length == 2 && input.substring(0, input.indexOf(":")).contains(",")) {
            portfolio = portAndBench[0].split("\\|");
            bench = portAndBench[1].split("\\|");
        } else if (input.substring(0, input.indexOf(":")).contains(",")) { // no assets in benchmark
            portfolio = portAndBench[0].split("\\|");
            bench = new String[0];
        } else { // no assets in portfolio
            portfolio = new String[0];
            bench = portAndBench[1].split("\\|");
        }

        checkAsset(portfolio, portBond, portStock);
        checkAsset(bench, benchBond, benchStock);
    }

    /**
     * Compare assets in the portfolio and benchmark to help decide if we should buy more or sell
     * 
     * @param port
     * @param bench
     */
    public static void comparePortBench(ArrayList<Asset> port, ArrayList<Asset> bench) {
        int portIndex = 0;
        int benchIndex = 0;
        // compare assets in portfolio and benchmark
        while (portIndex < port.size() || benchIndex < bench.size()) {
            if (portIndex >= port.size()) { // remaining assets in benchmark not in portfolio
                for (int i = benchIndex; i < bench.size(); i++) {
                    Asset tmp = bench.get(i);
                    buyList.add("BUY," + tmp.getName() + "," + tmp.getType() + ","
                                    + tmp.getShare());
                }
                break;
            }
            if (benchIndex >= bench.size()) { // remaining assets in portfolio not in benchmark
                for (int i = portIndex; i < port.size(); i++) {
                    Asset tmp = port.get(i);
                    sellList.add("SELL," + tmp.getName() + "," + tmp.getType() + ","
                                    + tmp.getShare());
                }
                break;
            }
            Asset portAsset = port.get(portIndex);
            Asset benchAsset = bench.get(benchIndex);
            // compare the number of share of assets in both portfolio and benchmark
            if (portAsset.getName().compareTo(benchAsset.getName()) == 0) {
                if (portAsset.getShare() < benchAsset.getShare()) { // less than expected
                    buyList.add("BUY," + portAsset.getName() + "," + portAsset.getType() + ","
                                    + (benchAsset.getShare() - portAsset.getShare()));
                } else if (portAsset.getShare() > benchAsset.getShare()) { // more than expected
                    sellList.add("SELL," + portAsset.getName() + "," + portAsset.getType() + ","
                                    + (portAsset.getShare() - benchAsset.getShare()));
                }
                portIndex++;
                benchIndex++;
            }
            // this asset is in portfolio, but not in benchmark
            else if (portAsset.getName().compareTo(benchAsset.getName()) < 0) {
                sellList.add("SELL," + portAsset.getName() + "," + portAsset.getType() + ","
                                + portAsset.getShare());
                portIndex++;
            }
            // the asset in benchmark is not in portfolio
            else if (portAsset.getName().compareTo(benchAsset.getName()) > 0) {
                buyList.add("BUY," + benchAsset.getName() + "," + benchAsset.getType() + ","
                                + benchAsset.getShare());
                benchIndex++;
            }
        }
    }

    public static void matchBenchmark(String input) {
        splitPortBench(input);
        Collections.sort(portBond);
        Collections.sort(portStock);
        Collections.sort(benchBond);
        Collections.sort(benchStock);
        comparePortBench(portBond, benchBond);
        comparePortBench(portStock, benchStock);
        if (sellList.size() > 0) {
            for (int j = 0; j < sellList.size(); j++)
                System.out.println(sellList.get(j));
        }
        if (buyList.size() > 0) {
            for (int j = 0; j < buyList.size(); j++)
                System.out.println(buyList.get(j));
        }
    }

    /**
     * check if this asset is a stock
     * 
     * @param input
     * @return
     */
    public static boolean isStock(String input) {
        if (input.toLowerCase().contains("stock"))
            return true;
        return false;
    }

    /**
     * check if this asset is a bond
     * 
     * @param input
     * @return
     */
    public static boolean isBond(String input) {
        if (input.toLowerCase().contains("bond"))
            return true;
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40136685/article/details/98746793