京东笔试真题

# 京东笔试真题

# 🏢 公司简介

京东是中国领先的电商和技术服务企业,笔试题目注重算法基础、系统设计和电商业务理解。

# 📝 题目特点

  • 电商场景:结合购物、物流、金融等业务场景
  • 算法扎实:考查数据结构和算法的深度理解
  • 系统设计:关注大规模分布式系统架构
  • 性能优化:重视算法效率和系统性能

# 🎯 2024年春招真题

# 题目1:商品库存管理系统 🟡

题目描述: 设计一个商品库存管理系统,支持商品入库、出库、查询库存等操作,并处理并发访问。

输入:

  • 操作序列(入库、出库、查询)
  • 商品ID和数量
  • 并发访问请求

输出:

  • 操作结果
  • 实时库存状态

解题思路:

class InventoryManager {
    private final Map<String, AtomicInteger> inventory;
    private final Map<String, ReentrantReadWriteLock> locks;
    private final Map<String, List<InventoryOperation>> operationLog;
    
    public InventoryManager() {
        this.inventory = new ConcurrentHashMap<>();
        this.locks = new ConcurrentHashMap<>();
        this.operationLog = new ConcurrentHashMap<>();
    }
    
    public boolean addStock(String productId, int quantity) {
        ReentrantReadWriteLock lock = locks.computeIfAbsent(productId, 
            k -> new ReentrantReadWriteLock());
        
        lock.writeLock().lock();
        try {
            AtomicInteger currentStock = inventory.computeIfAbsent(productId, 
                k -> new AtomicInteger(0));
            int newStock = currentStock.addAndGet(quantity);
            
            // 记录操作日志
            logOperation(productId, "ADD", quantity, newStock);
            
            return true;
        } finally {
            lock.writeLock().unlock();
        }
    }
    
    public boolean removeStock(String productId, int quantity) {
        ReentrantReadWriteLock lock = locks.computeIfAbsent(productId, 
            k -> new ReentrantReadWriteLock());
        
        lock.writeLock().lock();
        try {
            AtomicInteger currentStock = inventory.get(productId);
            if (currentStock == null || currentStock.get() < quantity) {
                return false; // 库存不足
            }
            
            int newStock = currentStock.addAndGet(-quantity);
            logOperation(productId, "REMOVE", quantity, newStock);
            
            return true;
        } finally {
            lock.writeLock().unlock();
        }
    }
    
    public int getStock(String productId) {
        ReentrantReadWriteLock lock = locks.computeIfAbsent(productId, 
            k -> new ReentrantReadWriteLock());
        
        lock.readLock().lock();
        try {
            AtomicInteger stock = inventory.get(productId);
            return stock != null ? stock.get() : 0;
        } finally {
            lock.readLock().unlock();
        }
    }
    
    public Map<String, Integer> getAllStock() {
        Map<String, Integer> result = new HashMap<>();
        for (Map.Entry<String, AtomicInteger> entry : inventory.entrySet()) {
            result.put(entry.getKey(), entry.getValue().get());
        }
        return result;
    }
    
    private void logOperation(String productId, String operation, int quantity, int newStock) {
        InventoryOperation op = new InventoryOperation(operation, quantity, newStock, System.currentTimeMillis());
        operationLog.computeIfAbsent(productId, k -> new ArrayList<>()).add(op);
    }
    
    static class InventoryOperation {
        String operation;
        int quantity;
        int resultStock;
        long timestamp;
        
        public InventoryOperation(String operation, int quantity, int resultStock, long timestamp) {
            this.operation = operation;
            this.quantity = quantity;
            this.resultStock = resultStock;
            this.timestamp = timestamp;
        }
    }
}

# 题目2:京东物流路径规划 🟠

题目描述: 给定配送中心、中转站和目的地的位置,设计算法找到最优的物流配送路径。

输入:

  • 配送网络图(节点和边的权重)
  • 起始配送中心
  • 目的地列表
  • 车辆容量限制

输出:

  • 最优配送路径
  • 总配送成本

解题思路:

class LogisticsOptimizer {
    static class Node {
        int id;
        double x, y;
        String type; // "center", "station", "destination"
        
        public Node(int id, double x, double y, String type) {
            this.id = id;
            this.x = x;
            this.y = y;
            this.type = type;
        }
        
        public double distanceTo(Node other) {
            return Math.sqrt(Math.pow(x - other.x, 2) + Math.pow(y - other.y, 2));
        }
    }
    
    static class Edge {
        int from, to;
        double cost;
        double capacity;
        
        public Edge(int from, int to, double cost, double capacity) {
            this.from = from;
            this.to = to;
            this.cost = cost;
            this.capacity = capacity;
        }
    }
    
    public List<List<Integer>> optimizeRoutes(List<Node> nodes, List<Edge> edges, 
                                            int startCenter, List<Integer> destinations, 
                                            double vehicleCapacity) {
        // 构建图
        Map<Integer, List<Edge>> graph = buildGraph(edges);
        
        // 计算所有节点间的最短路径
        Map<String, Double> shortestPaths = calculateAllShortestPaths(nodes, graph);
        
        // 使用遗传算法或模拟退火优化路径
        return optimizeWithGeneticAlgorithm(nodes, destinations, shortestPaths, vehicleCapacity);
    }
    
    private Map<Integer, List<Edge>> buildGraph(List<Edge> edges) {
        Map<Integer, List<Edge>> graph = new HashMap<>();
        for (Edge edge : edges) {
            graph.computeIfAbsent(edge.from, k -> new ArrayList<>()).add(edge);
        }
        return graph;
    }
    
    private Map<String, Double> calculateAllShortestPaths(List<Node> nodes, Map<Integer, List<Edge>> graph) {
        Map<String, Double> distances = new HashMap<>();
        
        // 使用Floyd-Warshall算法计算所有节点间最短路径
        int n = nodes.size();
        double[][] dist = new double[n][n];
        
        // 初始化距离矩阵
        for (int i = 0; i < n; i++) {
            Arrays.fill(dist[i], Double.MAX_VALUE);
            dist[i][i] = 0;
        }
        
        // 填充直接连接的边
        for (List<Edge> edgeList : graph.values()) {
            for (Edge edge : edgeList) {
                dist[edge.from][edge.to] = Math.min(dist[edge.from][edge.to], edge.cost);
            }
        }
        
        // Floyd-Warshall算法
        for (int k = 0; k < n; k++) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if (dist[i][k] != Double.MAX_VALUE && dist[k][j] != Double.MAX_VALUE) {
                        dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);
                    }
                }
            }
        }
        
        // 存储结果
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                distances.put(i + "-" + j, dist[i][j]);
            }
        }
        
        return distances;
    }
    
    private List<List<Integer>> optimizeWithGeneticAlgorithm(List<Node> nodes, 
                                                           List<Integer> destinations, 
                                                           Map<String, Double> distances, 
                                                           double vehicleCapacity) {
        // 简化版遗传算法实现
        List<List<Integer>> bestRoutes = new ArrayList<>();
        
        // 使用贪心算法作为初始解
        List<Integer> remaining = new ArrayList<>(destinations);
        int currentPos = 0; // 起始配送中心
        
        while (!remaining.isEmpty()) {
            List<Integer> currentRoute = new ArrayList<>();
            currentRoute.add(currentPos);
            double currentLoad = 0;
            
            while (!remaining.isEmpty() && currentLoad < vehicleCapacity) {
                // 找到最近的未访问目的地
                int nearest = findNearestDestination(currentPos, remaining, distances);
                if (nearest != -1) {
                    currentRoute.add(nearest);
                    remaining.remove(Integer.valueOf(nearest));
                    currentPos = nearest;
                    currentLoad += 1; // 假设每个目的地的货物重量为1
                }
            }
            
            bestRoutes.add(currentRoute);
            currentPos = 0; // 返回配送中心
        }
        
        return bestRoutes;
    }
    
    private int findNearestDestination(int currentPos, List<Integer> remaining, 
                                     Map<String, Double> distances) {
        int nearest = -1;
        double minDistance = Double.MAX_VALUE;
        
        for (int dest : remaining) {
            String key = currentPos + "-" + dest;
            Double distance = distances.get(key);
            if (distance != null && distance < minDistance) {
                minDistance = distance;
                nearest = dest;
            }
        }
        
        return nearest;
    }
}

# 题目3:京东金融风控系统 🔴

题目描述: 设计一个实时风控系统,根据用户的交易行为、设备信息等特征,判断交易是否存在风险。

输入:

  • 用户交易记录
  • 设备指纹信息
  • 风控规则配置

输出:

  • 风险评分
  • 风控决策(通过/拒绝/人工审核)

解题思路:

class RiskControlSystem {
    static class Transaction {
        String userId;
        String deviceId;
        double amount;
        String location;
        long timestamp;
        String paymentMethod;
        
        public Transaction(String userId, String deviceId, double amount, 
                         String location, long timestamp, String paymentMethod) {
            this.userId = userId;
            this.deviceId = deviceId;
            this.amount = amount;
            this.location = location;
            this.timestamp = timestamp;
            this.paymentMethod = paymentMethod;
        }
    }
    
    static class RiskFeature {
        double frequencyScore;      // 交易频率分数
        double amountScore;         // 交易金额分数
        double locationScore;       // 地理位置分数
        double deviceScore;         // 设备风险分数
        double timeScore;           // 时间模式分数
        
        public double getTotalScore() {
            return frequencyScore * 0.25 + amountScore * 0.2 + 
                   locationScore * 0.2 + deviceScore * 0.2 + timeScore * 0.15;
        }
    }
    
    enum RiskDecision {
        PASS, REJECT, MANUAL_REVIEW
    }
    
    private Map<String, List<Transaction>> userTransactionHistory;
    private Map<String, Set<String>> deviceUserMapping;
    private Map<String, Integer> locationRiskLevel;
    
    public RiskControlSystem() {
        this.userTransactionHistory = new HashMap<>();
        this.deviceUserMapping = new HashMap<>();
        this.locationRiskLevel = new HashMap<>();
        initializeRiskData();
    }
    
    public RiskDecision evaluateTransaction(Transaction transaction) {
        // 提取风险特征
        RiskFeature features = extractRiskFeatures(transaction);
        
        // 计算风险分数
        double riskScore = features.getTotalScore();
        
        // 更新历史记录
        updateTransactionHistory(transaction);
        
        // 做出风控决策
        return makeRiskDecision(riskScore, transaction);
    }
    
    private RiskFeature extractRiskFeatures(Transaction transaction) {
        RiskFeature features = new RiskFeature();
        
        // 1. 交易频率特征
        features.frequencyScore = calculateFrequencyScore(transaction);
        
        // 2. 交易金额特征
        features.amountScore = calculateAmountScore(transaction);
        
        // 3. 地理位置特征
        features.locationScore = calculateLocationScore(transaction);
        
        // 4. 设备风险特征
        features.deviceScore = calculateDeviceScore(transaction);
        
        // 5. 时间模式特征
        features.timeScore = calculateTimeScore(transaction);
        
        return features;
    }
    
    private double calculateFrequencyScore(Transaction transaction) {
        List<Transaction> history = userTransactionHistory.getOrDefault(
            transaction.userId, new ArrayList<>());
        
        // 计算最近1小时内的交易次数
        long oneHourAgo = transaction.timestamp - 3600000; // 1小时 = 3600000毫秒
        long recentTransactions = history.stream()
            .mapToLong(t -> t.timestamp)
            .filter(t -> t > oneHourAgo)
            .count();
        
        // 频率越高,风险分数越高
        if (recentTransactions > 10) return 0.9;
        if (recentTransactions > 5) return 0.6;
        if (recentTransactions > 2) return 0.3;
        return 0.1;
    }
    
    private double calculateAmountScore(Transaction transaction) {
        List<Transaction> history = userTransactionHistory.getOrDefault(
            transaction.userId, new ArrayList<>());
        
        if (history.isEmpty()) {
            // 新用户大额交易风险较高
            return transaction.amount > 1000 ? 0.8 : 0.2;
        }
        
        // 计算用户历史平均交易金额
        double avgAmount = history.stream()
            .mapToDouble(t -> t.amount)
            .average()
            .orElse(0);
        
        // 当前交易金额与历史平均值的比率
        double ratio = transaction.amount / (avgAmount + 1);
        
        if (ratio > 10) return 0.9;  // 超过平均值10倍
        if (ratio > 5) return 0.7;   // 超过平均值5倍
        if (ratio > 2) return 0.4;   // 超过平均值2倍
        return 0.1;
    }
    
    private double calculateLocationScore(Transaction transaction) {
        // 根据地理位置的风险等级评分
        int riskLevel = locationRiskLevel.getOrDefault(transaction.location, 1);
        
        // 检查是否为异地交易
        List<Transaction> history = userTransactionHistory.getOrDefault(
            transaction.userId, new ArrayList<>());
        
        boolean isRemoteTransaction = history.stream()
            .noneMatch(t -> t.location.equals(transaction.location));
        
        double baseScore = riskLevel * 0.2; // 基础地区风险
        double remoteScore = isRemoteTransaction ? 0.3 : 0; // 异地交易风险
        
        return Math.min(baseScore + remoteScore, 1.0);
    }
    
    private double calculateDeviceScore(Transaction transaction) {
        Set<String> usersOnDevice = deviceUserMapping.getOrDefault(
            transaction.deviceId, new HashSet<>());
        
        // 设备关联的用户数量越多,风险越高
        if (usersOnDevice.size() > 10) return 0.9;
        if (usersOnDevice.size() > 5) return 0.6;
        if (usersOnDevice.size() > 2) return 0.3;
        return 0.1;
    }
    
    private double calculateTimeScore(Transaction transaction) {
        // 检查是否在异常时间段交易(如深夜)
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(transaction.timestamp);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        
        // 深夜时段(0-6点)风险较高
        if (hour >= 0 && hour <= 6) return 0.6;
        // 正常时段风险较低
        return 0.1;
    }
    
    private RiskDecision makeRiskDecision(double riskScore, Transaction transaction) {
        if (riskScore >= 0.8) {
            return RiskDecision.REJECT;
        } else if (riskScore >= 0.5) {
            return RiskDecision.MANUAL_REVIEW;
        } else {
            return RiskDecision.PASS;
        }
    }
    
    private void updateTransactionHistory(Transaction transaction) {
        userTransactionHistory.computeIfAbsent(transaction.userId, 
            k -> new ArrayList<>()).add(transaction);
        deviceUserMapping.computeIfAbsent(transaction.deviceId, 
            k -> new HashSet<>()).add(transaction.userId);
    }
    
    private void initializeRiskData() {
        // 初始化地区风险等级(示例数据)
        locationRiskLevel.put("Beijing", 1);
        locationRiskLevel.put("Shanghai", 1);
        locationRiskLevel.put("Guangzhou", 1);
        locationRiskLevel.put("Unknown", 5);
    }
}

# 🔍 历年高频考点

# 算法类

  • 动态规划(背包问题、最优化问题)
  • 图算法(最短路径、网络流)
  • 排序和查找算法
  • 字符串处理算法

# 数据结构类

  • 线程安全的数据结构
  • 缓存设计(LRU、LFU)
  • 树结构(B+树、红黑树)
  • 哈希表和一致性哈希

# 系统设计类

  • 分布式系统架构
  • 数据库设计和优化
  • 缓存策略
  • 消息队列

# 💡 备考建议

  1. 基础扎实:重点掌握数据结构和算法基础
  2. 业务理解:了解电商和金融业务场景
  3. 系统思维:培养大规模系统设计能力
  4. 代码质量:注重代码的健壮性和可维护性
  5. 性能意识:时刻考虑算法和系统的性能优化