SRC 二分插入代码

本文介绍了一种精确匹配算法的实现过程,该算法通过遍历列表并比较元素值来找到最佳匹配项,同时考虑到值的范围限制,并返回最接近目标值的元素。
int low = 0;
int high = list.size() - 1;
int mid = 0;

int matchMid = -1;
FightRequestReq matchFightRequestReq = null;

while (low <= high) {
   mid = (low + high) >>> 1;
   int midVal = list.get(mid).getCompetitionVo().getFightValue();
   
   if (midVal >= req.getCompetitionVo().getPrefixValue() && midVal <= req.getCompetitionVo().getSuffixValue()) {
    // 匹配成功
    if (matchFightRequestReq == null) {
    matchFightRequestReq = list.get(mid);
    matchMid = mid;
    } else {
    if (Math.abs(midVal - req.getCompetitionVo().getFightValue()) < Math.abs(matchFightRequestReq.getCompetitionVo().getFightValue() - req.getCompetitionVo().getFightValue())) {
    // 匹配到更接近的值
    matchFightRequestReq = list.get(mid);
    matchMid = mid;
    } else {
    // 非最优值,继续匹配
    }
    }
    }


   if (midVal < req.getCompetitionVo().getFightValue()) {
    low = mid + 1;
   
    if (low > high) {
    if (midVal < req.getCompetitionVo().getPrefixValue() || midVal > req.getCompetitionVo().getSuffixValue()) {
    if (matchFightRequestReq != null) {
    return list.remove(matchMid);
    } else {
    return null;
    }
    } else {
    if (matchFightRequestReq != null) {
    if (Math.abs(midVal - req.getCompetitionVo().getFightValue()) < Math.abs(matchFightRequestReq.getCompetitionVo().getFightValue() - req.getCompetitionVo().getFightValue())) {
    // 匹配到更接近的值
    return list.remove(mid);
    } else {
    return list.remove(matchMid);
    }
    } else {
    return list.remove(mid);
    }
    }
    }
   } else if (midVal > req.getCompetitionVo().getFightValue()) {
    high = mid - 1;
   
    if (low > high) {
    if (midVal < req.getCompetitionVo().getPrefixValue() || midVal > req.getCompetitionVo().getSuffixValue()) {
    if (matchFightRequestReq != null) {
    return list.remove(matchMid);
    } else {
    return null;
    }
    } else {
    if (matchFightRequestReq != null) {
    if (Math.abs(midVal - req.getCompetitionVo().getFightValue()) < Math.abs(matchFightRequestReq.getCompetitionVo().getFightValue() - req.getCompetitionVo().getFightValue())) {
    // 匹配到更接近的值
    return list.remove(mid);
    } else {
    return list.remove(matchMid);
    }
    } else {
    return list.remove(mid);
    }
    }
    }
   } else {
    return list.remove(mid);
   }
}

if (matchFightRequestReq != null) {
return list.remove(matchMid);
}

return null;
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值