未完成--Sum of Pairs

本文介绍了一个算法挑战:从整数列表中找出首次出现且相加等于特定目标值的两个数。探讨了遍历方法及其效率考量,适用于列表长度可达千万级别的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Sum of Pairs

Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum.

sum_pairs([11, 3, 7, 5],         10)
#              ^--^      3 + 7 = 10
== [3, 7]

sum_pairs([4, 3, 2, 3, 4],         6)
#          ^-----^         4 + 2 = 6, indices: 0, 2 *
#             ^-----^      3 + 3 = 6, indices: 1, 3
#                ^-----^   2 + 4 = 6, indices: 2, 4
#  * entire pair is earlier, and therefore is the correct answer
== [4, 2]

sum_pairs([0, 0, -2, 3], 2)
#  there are no pairs of values that can be added to produce 2.
== None/nil/undefined (Based on the language)

sum_pairs([10, 5, 2, 3, 7, 5],         10)
#              ^-----------^   5 + 5 = 10, indices: 1, 5
#                    ^--^      3 + 7 = 10, indices: 3, 4 *
#  * entire pair is earlier, and therefore is the correct answer
== [3, 7]
Negative numbers and duplicate numbers can and will appear.

NOTE: There will also be lists tested of lengths upwards of 10,000,000 elements. Be sure your code doesn't time out.

代码

var sum_pairs = function (ints, s) {
    for (var i = 0, l = ints.length, r = []; i < l; i++) {
        for (var j = 1; j < l; j++) {
            if (ints[i] + ints[j] == s) {
                if (r[1]==null||j + i >= r[0] + r[1]) {
                    r[0] = i;
                    r[1] = j;
                }
            }
        }
    }
    return r[0]?[ints[r[0]], ints[r[1]]]:"undefined for sum = " + s;
}
function dual_side_fragment_classification() % 初始化 clc; clear; close all; warning off; % 选择文件夹 folder_path = uigetdir('', '选择包含双面碎片的文件夹(附件5)'); if folder_path == 0 error('用户取消选择'); end %% 1. 加载并配对正反面文件 [pairs, unmatched] = load_and_pair_fragments(folder_path); fprintf('已加载 %d 对有效碎片,%d 个未匹配碎片\n', size(pairs,1), length(unmatched)); %% 2. 提取行特征(仅使用正面) features = zeros(size(pairs,1), 100); % 100维特征 parfor i = 1:size(pairs,1) img = preprocess_image(fullfile(folder_path, pairs{i,1})); features(i,:) = extract_row_features(img); end %% 3. 行分类(22行) row_labels = classify_rows(features, 14); %% 4. 生成分类结果表 create_result_table(folder_path, pairs, row_labels, unmatched); fprintf('分类完成!结果已保存到:%s\n', fullfile(folder_path, 'classification_results.xlsx')); end %% 文件加载与配对函数(修改版) function [pairs, unmatched] = load_and_pair_fragments(folder) % 获取所有.bmp文件 file_list = dir(fullfile(folder, '*.bmp')); if isempty(file_list) file_list = dir(fullfile(folder, '*.BMP')); end % 使用结构数组替代Map all_files = struct('id', {}, 'a', '', 'b', ''); % 先索引所有文件 for i = 1:length(file_list) [~, name, ~] = fileparts(file_list(i).name); id_str = name(1:end-1); % 去掉最后一位a/b id_num = str2double(id_str); % 查找或创建条目 found = false; for j = 1:length(all_files) if all_files(j).id == id_num if endsWith(name, 'a') all_files(j).a = file_list(i).name; else all_files(j).b = file_list(i).name; end found = true; break; end end if ~found new_entry.id = id_num; if endsWith(name, 'a') new_entry.a = file_list(i).name; new_entry.b = ''; else new_entry.a = ''; new_entry.b = file_list(i).name; end all_files(end+1) = new_entry; end end % 配对正反面 pairs = cell(0,2); unmatched = {}; for i = 1:length(all_files) if ~isempty(all_files(i).a) && ~isempty(all_files(i).b) pairs(end+1,:) = {all_files(i).a, all_files(i).b}; elseif ~isempty(all_files(i).a) unmatched{end+1} = all_files(i).a; else unmatched{end+1} = all_files(i).b; end end % 按编号排序 [~, idx] = sort([all_files.id]); all_files = all_files(idx); % 重新组织已排序的数据 pairs = cell(0,2); unmatched = {}; for i = 1:length(all_files) if ~isempty(all_files(i).a) && ~isempty(all_files(i).b) pairs(end+1,:) = {all_files (i).a, all_files(i).b}; elseif ~isempty(all_files(i).a) unmatched{end+1} = all_files(i).a; else unmatched{end+1} = all_files(i).b; end end end %% 图像预处理(适配.bmp) function img = preprocess_image(filepath) img = imread(filepath); if size(img,3) == 3 img = rgb2gray(img); end img = imbinarize(img, 'adaptive'); img = bwareaopen(img, 20); end %% 行特征提取(保持不变) function features = extract_row_features(bw_img) h_proj = sum(~bw_img, 2); features = imresize(h_proj, [100, 1])'; end %% 行分类函数(保持不变) function labels = classify_rows(features, k) [~, score] = pca(features); [labels, ~] = kmeans(score(:,1:10), k, 'Replicates', 5); end %% 创建结果表格(修改版) function create_result_table(folder, pairs, row_labels, unmatched) % 初始化22x19的cell数组 result_front = cell(22, 19); result_back = cell(22, 19); % 按行组织碎片 for row = 1:max(row_labels) idx = find(row_labels == row); row_pairs = pairs(idx,:); % 填充到表格(最多19列) for col = 1:min(19, size(row_pairs,1)) % 正面碎片(去掉扩展名) [~, name_front, ~] = fileparts(row_pairs{col,1}); result_front{row, col} = name_front; % 对应背面碎片 [~, name_back, ~] = fileparts(row_pairs{col,2}); result_back{row, col} = name_back; end end % 写入Excel文件 output_file = fullfile(folder, 'classification_results.xlsx'); % 正面碎片分类 writecell({'正面碎片分类结果(22行×19列)'}, output_file, 'Sheet', '正面', 'Range', 'A1'); writecell(result_front, output_file, 'Sheet', '正面', 'Range', 'A2'); % 背面碎片分类 writecell({'背面碎片分类(对应正面位置)'}, output_file, 'Sheet', '背面', 'Range', 'A1'); writecell(result_back, output_file, 'Sheet', '背面', 'Range', 'A2'); % 未匹配碎片 if ~isempty(unmatched) unmatched_names = cellfun(@(x) x(1:end-4), unmatched, 'UniformOutput', false); writecell({'未匹配碎片(缺少对应面)'}, output_file, 'Sheet', '未匹配', 'Range', 'A1'); writecell(unmatched_names, output_file, 'Sheet', '未匹配', 'Range', 'A2'); end % 添加说明 notes = { '说明:'; '1. 文件格式要求:000a.bmp, 000b.bmp,...,208a.bmp,208b.bmp'; '2. 每行最多显示19个碎片,实际数量可能不同'; '3. 未匹配碎片可能缺少对应正反面文件'; '4. 需要人工验证跨行分类准确性'}; writecell(notes, output_file, 'Sheet', '说明', 'Range', 'A1'); end这个代码有的图片的正反面分不出来请修改以解决这个问题 回答 向我提问的人太多了。正在努力扩容中,请稍后再试。 function dual_side_fragment_classification() % 初始化 clc; clear; close all; warning off; % 选择文件夹 folder_path = uigetdir(‘’, ‘选择包含双面碎片的文件夹(附件5)’); if folder_path == 0 error(‘用户取消选择’); end %% 1. 加载并配对正反面文件 [pairs, unmatched] = load_and_pair_fragments(folder_path); fprintf(‘已加载 %d 对有效碎片,%d 个未匹配碎片\n’, size(pairs,1), length(unmatched)); %% 2. 提取行特征(仅使用正面) features = zeros(size(pairs,1), 100); % 100维特征 parfor i = 1:size(pairs,1) img = preprocess_image(fullfile(folder_path, pairs{i,1})); features(i,:) = extract_row_features(img); end %% 3. 行分类(22行) row_labels = classify_rows(features, 14); %% 4. 生成分类结果表 create_result_table(folder_path, pairs, row_labels, unmatched); fprintf(‘分类完成!结果已保存到:%s\n’, fullfile(folder_path, ‘classification_results.xlsx’)); end %% 文件加载与配对函数(修改版) function [pairs, unmatched] = load_and_pair_fragments(folder) % 获取所有.bmp文件 file_list = dir(fullfile(folder, ‘.bmp’)); if isempty(file_list) file_list = dir(fullfile(folder, '.BMP’)); end % 使用结构数组替代Map all_files = struct(‘id’, {}, ‘a’, ‘’, ‘b’, ‘’); % 先索引所有文件 for i = 1:length(file_list) [~, name, ~] = fileparts(file_list(i).name); id_str = name(1:end-1); % 去掉最后一位a/b id_num = str2double(id_str); % 查找或创建条目 found = false; for j = 1:length(all_files) if all_files(j).id == id_num if endsWith(name, ‘a’) all_files(j).a = file_list(i).name; else all_files(j).b = file_list(i).name; end found = true; break; end end if ~found new_entry.id = id_num; if endsWith(name, ‘a’) new_entry.a = file_list(i).name; new_entry.b = ‘’; else new_entry.a = ‘’; new_entry.b = file_list(i).name; end all_files(end+1) = new_entry; end end % 配对正反面 pairs = cell(0,2); unmatched = {}; for i = 1:length(all_files) if ~isempty(all_files(i).a) && ~isempty(all_files(i).b) pairs(end+1,:) = {all_files(i).a, all_files(i).b}; elseif ~isempty(all_files(i).a) unmatched{end+1} = all_files(i).a; else unmatched{end+1} = all_files(i).b; end end % 按编号排序 [~, idx] = sort([all_files.id]); all_files = all_files(idx); % 重新组织已排序的数据 pairs = cell(0,2); unmatched = {}; for i = 1:length(all_files) if ~isempty(all_files(i).a) && ~isempty(all_files(i).b) pairs(end+1,:) = {all_files (i).a, all_files(i).b}; elseif ~isempty(all_files(i).a) unmatched{end+1} = all_files(i).a; else unmatched{end+1} = all_files(i).b; end end end %% 图像预处理(适配.bmp) function img = preprocess_image(filepath) img = imread(filepath); if size(img,3) == 3 img = rgb2gray(img); end img = imbinarize(img, ‘adaptive’); img = bwareaopen(img, 20); end %% 行特征提取(保持不变) function features = extract_row_features(bw_img) h_proj = sum(~bw_img, 2); features = imresize(h_proj, [100, 1])'; end %% 行分类函数(保持不变) function labels = classify_rows(features, k) [~, score] = pca(features); [labels, ~] = kmeans(score(:,1:10), k, ‘Replicates’, 5); end %% 创建结果表格(修改版) function create_result_table(folder, pairs, row_labels, unmatched) % 初始化22x19的cell数组 result_front = cell(22, 19); result_back = cell(22, 19); % 按行组织碎片 for row = 1:max(row_labels) idx = find(row_labels == row); row_pairs = pairs(idx,:); % 填充到表格(最多19列) for col = 1:min(19, size(row_pairs,1)) % 正面碎片(去掉扩展名) [~, name_front, ~] = fileparts(row_pairs{col,1}); result_front{row, col} = name_front; % 对应背面碎片 [~, name_back, ~] = fileparts(row_pairs{col,2}); result_back{row, col} = name_back; end end % 写入Excel文件 output_file = fullfile(folder, ‘classification_results.xlsx’); % 正面碎片分类 writecell({‘正面碎片分类结果(22行×19列)’}, output_file, ‘Sheet’, ‘正面’, ‘Range’, ‘A1’); writecell(result_front, output_file, ‘Sheet’, ‘正面’, ‘Range’, ‘A2’); % 背面碎片分类 writecell({‘背面碎片分类(对应正面位置)’}, output_file, ‘Sheet’, ‘背面’, ‘Range’, ‘A1’); writecell(result_back, output_file, ‘Sheet’, ‘背面’, ‘Range’, ‘A2’); % 未匹配碎片 if ~isempty(unmatched) unmatched_names = cellfun(@(x) x(1:end-4), unmatched, ‘UniformOutput’, false); writecell({‘未匹配碎片(缺少对应面)’}, output_file, ‘Sheet’, ‘未匹配’, ‘Range’, ‘A1’); writecell(unmatched_names, output_file, ‘Sheet’, ‘未匹配’, ‘Range’, ‘A2’); end % 添加说明 notes = { ‘说明:’; ‘1. 文件格式要求:000a.bmp, 000b.bmp,…,208a.bmp,208b.bmp’; ‘2. 每行最多显示19个碎片,实际数量可能不同’; ‘3. 未匹配碎片可能缺少对应正反面文件’; ‘4. 需要人工验证跨行分类准确性’}; writecell(notes, output_file, ‘Sheet’, ‘说明’, ‘Range’, ‘A1’); end这个代码有的图片的正反面分不出来请修改以解决这个问题,我的代码是对于碎片拼接的,我的碎片地址是D:\BaiduNetdiskDownload\MATLAB R2024a\bin\project\附件5
07-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liugang0605

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值