发布于2019-07-16 19:43 阅读(5853) 评论(0) 点赞(49) 收藏(71)
原题:
有两个序列a,b,大小都为n,序列元素的值任意整形数,无序;
要求:通过交换a,b中的元素,使[序列a元素的和]与[序列b元素的和]之间的差最小
限时十分钟以内
尝试解答,coding和debug共用了约1个小时,呵呵,去不了华为了。
获取最小差的函数,还可以优化,现在的时间复杂度是n×n,估计可以优化到n×lg(n)
网上有一种解答方法,认为最小值是负数,排序之后,截成两段,小数序列-大数序列即可。难道,难道,这才是本题十分钟解出的奥义?!
我的代码如下,算法很简单(我的算法不对,请列位看官参考评论中张三的):
''' Created on 2010-6-21 @author: maodouzi ''' import random def getMinSubKeys(leftArray, rightArray): if (sum(leftArray) > sum(rightArray)): subArray = leftArray minuendArray = rightArray subFlag = True elif (sum(leftArray) < sum(rightArray)): subArray = rightArray minuendArray = leftArray subFlag = False else: return None minSubNum = (sum(subArray) - sum(minuendArray)) / 2.0 tmpMinSubResult = sum(subArray) subKey = 0 minuendKey = 0 for i_key, i in enumerate(subArray): for j_key, j in enumerate(minuendArray): if (abs(i - j - minSubNum) < tmpMinSubResult): tmpMinSubResult = abs(i - j - minSubNum) subKey = i_key minuendKey = j_key if (subFlag == True): return (subKey, minuendKey) else: return (minuendKey, subKey) if __name__ == '__main__': aa = range(20); bb = [random.randint(0, 100) for i in aa] bb.sort(reverse=True) print aa print bb leftArray = [] rightArray = [] while (len(bb)): tmpNumArray = bb[0:2] bb = bb[2:] if (sum(leftArray) <= sum(rightArray)): leftArray.append(tmpNumArray[0]) rightArray.append(tmpNumArray[1]) else : leftArray.append(tmpNumArray[1]) rightArray.append(tmpNumArray[0]) leftArray.sort() rightArray.sort() tmpKeyArray = getMinSubKeys(leftArray, rightArray) if (tmpKeyArray == None): continue else: orgSubNum = abs(sum(leftArray) - sum(rightArray)); newSubNum = abs(orgSubNum + (rightArray[tmpKeyArray[1]] - leftArray[tmpKeyArray[0]]) * 2) if (newSubNum < orgSubNum): tmpNum = leftArray[tmpKeyArray[0]] leftArray[tmpKeyArray[0]] = rightArray[tmpKeyArray[1]] rightArray[tmpKeyArray[1]] = tmpNum leftArray.sort() rightArray.sort() print leftArray, sum(leftArray) print rightArray, sum(rightArray) print "The subNum is: %d" % abs(sum(leftArray) - sum(rightArray))
输出结果如下:
[93, 91, 90, 82, 81, 74, 74, 74, 74, 68, 60, 57, 49, 48, 48, 45, 36, 35, 29, 22] [22, 36, 48, 48, 60, 68, 74, 81, 82, 93] 612 [29, 35, 45, 49, 57, 74, 74, 74, 90, 91] 618 The subNum is: 6
作者:把镜子打碎
链接:https://www.pythonheidong.com/blog/article/1710/4914a44473a7781e163e/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!