校招算法笔面试 | 华为机试-数据分类处理

题目## 题目

题目链接

解题思路

这是一个数组分组问题,需要将数组分成两组,使得:

  1. 所有5的倍数必须在其中一个组中
  2. 所有3的倍数(不包括5的倍数)在另一个组中
  3. 其他数字可以任意分配
  4. 要求两组各元素加起来的和相等

实现思路

  1. 首先将数组分成三类:

    • 5的倍数(必须在第一组)
    • 3的倍数(必须在第二组)
    • 其他数字(可以任意分配)
  2. 使用DFS或动态规划尝试分配其他数字,使两组和相等


代码

#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    bool canPartition(vector<int>& nums) {
        // 去掉0
        vector<int> nonZeroNums;
        for (int num : nums) {
            if (num != 0) nonZeroNums.push_back(num);
        }
        
        // 分类统计
        vector<int> group5, group3, others;
        int sum5 = 0, sum3 = 0;
        
        for (int num : nonZeroNums) {
            if (num % 5 == 0) {
                group5.push_back(num);
                sum5 += num;
            } else if (num % 3 == 0) {
                group3.push_back(num);
                sum3 += num;
            } else {
                others.push_back(num);
            }
        }
        
        return dfs(others, 0, sum5 - sum3);
    }
    
private:
    bool dfs(vector<int>& nums, int index, int diff) {
        if (index == nums.size()) {
            return diff == 0;
        }
        
        // 尝试将当前数字加入第一组(5的倍数组)
        if (dfs(nums, index + 1, diff + nums[index])) {
            return true;
        }
        
        // 尝试将当前数字加入第二组(3的倍数组)
        if (dfs(nums, index + 1, diff - nums[index])) {
            return true;
        }
        
        return false;
    }
};

int main() {
    int n;
    while (cin >> n) {
        vector<int> nums(n);
        for (int i = 0; i < n; i++) {
            cin >> nums[i];
        }
        Solution sol;
        cout << (sol.canPartition(nums) ? "true" : "false") << endl;
    }
    return 0;
}
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = sc.nextInt();
            int[] nums = new int[n];
            for (int i = 0; i < n; i++) {
                nums[i] = sc.nextInt();
            }
            System.out.println(canPartition(nums) ? "true" : "false");
        }
    }
    
    public static boolean canPartition(int[] nums) {
        // 去掉0
        List<Integer> nonZeroNums = new ArrayList<>();
        for (int num : nums) {
            if (num != 0) nonZeroNums.add(num);
        }
        
        // 分类统计
        List<Integer> group5 = new ArrayList<>();
        List<Integer> group3 = new ArrayList<>();
        List<Integer> others = new ArrayList<>();
        int sum5 = 0, sum3 = 0;
        
        for (int num : nonZeroNums) {
            if (num % 5 == 0) {
                group5.add(num);
                sum5 += num;
            } else if (num % 3 == 0) {
                group3.add(num);
                sum3 += num;
            } else {
                others.add(num);
            }
        }
        
        return dfs(others, 0, sum5 - sum3);
    }
    
    private static boolean dfs(List<Integer> nums, int index, int diff) {
        if (index == nums.size()) {
            return diff == 0;
        }
        
        // 尝试将当前数字加入第一组(5的倍数组)
        if (dfs(nums, index + 1, diff + nums.get(index))) {
            return true;
        }
        
        // 尝试将当前数字加入第二组(3的倍数组)
        if (dfs(nums, index + 1, diff - nums.get(index))) {
            return true;
        }
        
        return false;
    }
}
def can_partition(nums):
    # 特殊处理0
    nums = [x for x in nums if x != 0]  # 去掉0
    
    # 分类统计
    group5 = []  # 5的倍数
    group3 = []  # 3的倍数(不含5的倍数)
    others = []  # 其他数
    
    for num in nums:
        if num % 5 == 0:
            group5.append(num)
        elif num % 3 == 0:
            group3.append(num)
        else:
            others.append(num)
    
    sum5 = sum(group5)
    sum3 = sum(group3)
    
    def dfs(index, diff):
        if index == len(others):
            return diff == 0
            
        # 尝试将当前数字加入第一组(5的倍数组)
        if dfs(index + 1, diff + others[index]):
            return True
            
        # 尝试将当前数字加入第二组(3的倍数组)
        if dfs(index + 1, diff - others[index]):
            return True
            
        return False
    
    return dfs(0, sum5 - sum3)

# 主程序
while True:
    try:
        n = int(input())
        nums = list(map(int, input().split()))
        print("true" if can_partition(nums) else "false")
    except:
        break

算法及复杂度

算法分析

  • 算法:DFS(深度优先搜索)
    1. 先将数组分成三类:5的倍数、3的倍数、其他数字
    2. 使用DFS尝试分配其他数字到两个组中
    3. 判断是否能使两组和相等

复杂度分析

  • 时间复杂度: O ( 2 n ) \mathcal{O}(2^n) O(2n) - 其中n是非3和5倍数的数字个数
  • 空间复杂度: O ( n ) \mathcal{O}(n) O(n) - 递归调用栈的深度

题目链接

解题思路

  1. 首先需要处理两个输入序列:原始序列I和规则序列R
  2. 对规则序列R进行排序和去重
  3. 对于R中的每个数字r:
    • 在I序列中查找包含r的所有数字
    • 记录这些数字在原序列中的位置
  4. 按照要求的格式输出结果:
    • 先输出总的匹配数量
    • 然后按R中数字的顺序输出匹配结果

代码

#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <algorithm>
using namespace std;

bool contains(int num, int target) {
    string numStr = to_string(num);
    string targetStr = to_string(target);
    return numStr.find(targetStr) != string::npos;
}

int main() {
    int n, m;
    while (cin >> n) {
        vector<int> I(n);
        for (int i = 0; i < n; i++) {
            cin >> I[i];
        }
        
        cin >> m;
        vector<int> R(m);
        for (int i = 0; i < m; i++) {
            cin >> R[i];
        }
        
        // 对R进行排序和去重
        set<int> uniqueR(R.begin(), R.end());
        vector<int> sortedR(uniqueR.begin(), uniqueR.end());
        
        vector<int> result;
        // 处理每个规则数字
        for (int r : sortedR) {
            vector<pair<int, int>> matches;  // (位置, 值)
            for (int i = 0; i < n; i++) {
                if (contains(I[i], r)) {
                    matches.push_back({i, I[i]});
                }
            }
            
            if (!matches.empty()) {
                result.push_back(r);
                result.push_back(matches.size());
                for (auto& match : matches) {
                    result.push_back(match.first);
                    result.push_back(match.second);
                }
            }
        }
        
        // 输出结果
        cout << result.size() << " ";
        for (int i = 0; i < result.size(); i++) {
            cout << result[i];
            if (i < result.size() - 1) cout << " ";
        }
        cout << endl;
    }
    return 0;
}
import java.util.*;

public class Main {
    private static boolean contains(int num, int target) {
        return String.valueOf(num).contains(String.valueOf(target));
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = sc.nextInt();
            int[] I = new int[n];
            for (int i = 0; i < n; i++) {
                I[i] = sc.nextInt();
            }
            
            int m = sc.nextInt();
            int[] R = new int[m];
            for (int i = 0; i < m; i++) {
                R[i] = sc.nextInt();
            }
            
            // 对R进行排序和去重
            TreeSet<Integer> uniqueR = new TreeSet<>();
            for (int r : R) uniqueR.add(r);
            
            List<Integer> result = new ArrayList<>();
            // 处理每个规则数字
            for (int r : uniqueR) {
                List<int[]> matches = new ArrayList<>();  // [位置, 值]
                for (int i = 0; i < n; i++) {
                    if (contains(I[i], r)) {
                        matches.add(new int[]{i, I[i]});
                    }
                }
                
                if (!matches.isEmpty()) {
                    result.add(r);
                    result.add(matches.size());
                    for (int[] match : matches) {
                        result.add(match[0]);
                        result.add(match[1]);
                    }
                }
            }
            
            // 输出结果
            System.out.print(result.size());
            for (int val : result) {
                System.out.print(" " + val);
            }
            System.out.println();
        }
    }
}
def contains(num, target):
    """检查数字num是否包含target作为子串"""
    num_str = str(num)
    target_str = str(target)
    return target_str in num_str

while True:
    try:
        # 读取序列I
        I = list(map(int, input().split()))
        n = I[0]
        I = I[1:]
        
        # 读取序列R
        R = list(map(int, input().split()))
        m = R[0]
        R = R[1:]
        
        # 对R进行排序和去重
        unique_R = sorted(set(R))
        
        result = []
        # 处理每个规则数字
        for r in unique_R:
            matches = []  # [(位置, 值)]
            for i in range(len(I)):
                if contains(I[i], r):
                    matches.append((i, I[i]))
            
            if matches:
                result.append(r)
                result.append(len(matches))
                for pos, val in matches:
                    result.append(pos)
                    result.append(val)
        
        # 输出结果
        print(len(result), end='')
        for i in range(len(result)):
            print(f" {result[i]}", end='')
        print()
            
    except EOFError:
        break

算法及复杂度

  • 算法:字符串匹配 + 排序
  • 时间复杂度: O ( m log ⁡ m + n ⋅ m ⋅ k ) \mathcal{O}(m \log m + n \cdot m \cdot k) O(mlogm+nmk),其中n是序列I的长度,m是序列R的长度,k是数字转字符串后的平均长度
  • 空间复杂度: O ( m + n ) \mathcal{O}(m + n) O(m+n),用于存储结果和临时数据
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值