[Interview with experts]——Written test questions (4 questions)

1. Split the collection

Title: Write a Java function to implement the function of obtaining data in batches (BService.get(List ids)). The specific requirements are as follows:
1) Provide a function BService.get(List ids), which supports the incoming of up to 100 ids;
2) Inside the BService.get((List ids) function, the incoming id list needs to be divided into batches (each 10 ids in a batch) to call the AService.get(List ids) function to obtain data;
3) The BService.get((List ids) function needs to return the combined result of all data obtained in batches, that is, a List containing all data;

The first way: implement the segmentation method yourself

import java.util.List;

public class AService {
    
    
    public List<Integer> get(List<Integer> ids){
    
    
        //业务处理
        return ids;
    }
}

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.List;

public class BService {
    
    

    public static List<Integer> get(List<Integer> ids){
    
    
        AService aService = new AService();
        if(ids == null || ids.size() == 0 || ids.size() > 100){
    
    
            throw new IllegalArgumentException("传入的ids大于100或者为空!");
        }
        List<Integer> result = new ArrayList<>();

        // 将ids分成大小为10的子列表,然后逐个调用AService.get方法
        for (List<Integer> sublist : partition(ids, 10)) {
    
    
            result.addAll(aService.get(sublist));
        }
        return result;

    }

    /**
     * 分割集合
     * @param list 集合
     * @param chunkSize 分割大小
     * @return
     */
    private static List<List<Integer>> partition(List<Integer> list ,Integer chunkSize){
    
    
        List<List<Integer>> partitions = new ArrayList<>();
        for (int i = 0; i < list.size(); i += chunkSize) {
    
    
            partitions.add(list.subList(i, Math.min(i + chunkSize, list.size())));
        }
        System.out.println(JSONObject.toJSONString(partitions));
        return partitions;
    }

    public static void main(String[] args) {
    
    
        ArrayList<Integer> testArray = new ArrayList<>();
        testArray.add(1);
        testArray.add(3);
        testArray.add(4);
        testArray.add(6);
        testArray.add(8);
        testArray.add(6);
        testArray.add(8);
        testArray.add(3);
        testArray.add(8);
        testArray.add(8);
        testArray.add(8);
        testArray.add(8);
        testArray.add(8);
        testArray.add(2);
        testArray.add(8);
        testArray.add(1);
        testArray.add(8);
        get(testArray);
    }
}

result:

[[1,3,4,6,8,6,8,3,8,8],[8,8,8,2,8,1,8]]

Second way: Use third-party dependencies

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>28.0-jre</version>
</dependency>
...
//list:集合 chunkSize分成的份数
Lists.partition(list,chunkSize);
...

2. Linked list calculation

You are given two non-empty linked lists, representing two non-negative integers. Each of their digits is stored sequentially, and each node can only store one digit.
Please subtract two numbers and return a linked list representing the subtraction result in the same form.
You can assume
1) Except for the number 0, neither number will start with 0.
2) The first number given must be greater than the second number.
Example:
Input: l1 = [9,8,7], l2 = [5,1,2]
Output: [4,7,5]
Explanation: 987-512 = 475

public class LinkedCalculate {
    
    
    public static LinkedList<Integer> subtract(LinkedList<Integer> l1, LinkedList<Integer> l2) {
    
    
        LinkedList<Integer> result = new LinkedList<>();
        //借位
        int borrow = 0;
        while (!l1.isEmpty() || !l2.isEmpty()) {
    
    
            int x = !l1.isEmpty() ? l1.removeLast() : 0;
            int y = !l2.isEmpty() ? l2.removeLast() : 0;

            int diff = x - y - borrow;

            if (diff < 0) {
    
    
                diff += 10;
                borrow = 1;
            } else {
    
    
                borrow = 0;
            }

            result.addFirst(diff);
        }
        // 移除前导零
        while (!result.isEmpty() && result.getFirst() == 0) {
    
    
            result.removeFirst();
        }
        return result;
    }
    public static void main(String[] args) {
    
    

        LinkedList<Integer> l1 = new LinkedList<>();
        l1.add(9);
        l1.add(8);
        l1.add(1);

        LinkedList<Integer> l2 = new LinkedList<>();
        l2.add(5);
        l2.add(1);
        l2.add(2);
        LinkedList<Integer> result = subtract(l1, l2);
        for (Integer digit : result) {
    
    
            System.out.print(digit);
        }
    }
}

3. String calculation

Provides a method that accepts two strings, which are numbers. The function of this method is to add the two string values ​​and return them. Type conversion cannot be used.

public static String addStrings(String num1, String num2) {
    
    
        StringBuilder result = new StringBuilder();
        int carry = 0; // 进位初始化为0

        int i = num1.length() - 1;
        int j = num2.length() - 1;

        while (i >= 0 || j >= 0) {
    
    
            int x = (i >= 0) ? num1.charAt(i) - '0' : 0;
            int y = (j >= 0) ? num2.charAt(j) - '0' : 0;
            int sum = x + y + carry;
            // 计算进位
            carry = sum / 10; 
            // 添加当前位的数字到结果字符串
            result.append(sum % 10); 
            i--;
            j--;
        }

        if (carry > 0) {
    
    
        	// 如果最高位有进位,添加进位到结果字符串
            result.append(carry); 
        }
 		// 最后需要反转字符串得到正确的结果
        return result.reverse().toString();
    }

    public static void main(String[] args) {
    
    
        String num1 = "123";
        String num2 = "758";
        String sum = addStrings(num1, num2);
        System.out.println(sum); 

    }

result:

881

4. Find numbers that add to 0

Provide a method that accepts two arrays. The function of the method is to form a new array and return the numbers in the array that add up to 0. for example:

int a = {
    
    1,2,3};
int b = {
    
    -1,-2,-3};
返回:[[-1,1],[-2,2],[-3,3]]
 public static List<List<Integer>> findZeroSumArray(List<Integer> arr1,List<Integer> arr2) {
    
    
        List<List<Integer>> result = new ArrayList<>();
        for (int num : arr2) {
    
    
            List<Integer> resultList = new ArrayList<>();
            if (arr1.contains(-num)) {
    
    
                resultList.add(num);
                resultList.add(-num);
                result.add(resultList);
            }
        }
        return result;
    }


    public static void main(String[] args) {
    
    
        List<Integer> arr1 = Arrays.asList(1, 2, 3, -2, -1,-1);
        List<Integer> arr2 = Arrays.asList(-3, 4, -2, 1, 5);
        List<List<Integer>> zeroSumArray = findZeroSumArray(arr1, arr2);
        System.out.println(JSONObject.toJSONString(zeroSumArray));
    }

result:

[[-3,3],[-2,2],[1,-1]]

Guess you like

Origin blog.csdn.net/qq_42785250/article/details/133150068