python贪心算法 多天优化_华为Python面试题,贪心算法,当前非最优解 - InvisibleMiner02的专栏 - 博客频道 - CSDN...

题目:

有两个序列a,b, 大小都为n, 序列元素的值为任意整形数,无序:

要求: 通过交换a,b中的元素,是[序列a元素的和]与[序列b元素的和]之间的差最小。

(从我之前的一个博客搬迁过来,没什么问题吧?)

我李泽军Thomas的解答:

# this solution is based on greedy algorithm ,its result is not optimal.

# comparing the solution on the web, this solution have better results for some test suit, but

# worse results for some , and the same for others

# def min_custom(a,b,n):

def min_custom(new):

# new = a + b

# print new

# greedy algorithm first

a = []

b = []

# print sb

length = len(new)/2

for i in xrange(length):

sa = sum(a)

sb = sum(b)

pop_a = new.pop()

pop_b = new.pop()

bigger = max(pop_a,pop_b)

smaller = min(pop_a,pop_b)

if(sa > sb):

a.append(smaller)

b.append(bigger)

else:

a.append(bigger)

b.append(smaller)

print a,b

difference = sum(a) - sum(b)

print difference

# a = [3,4,5]

# b= [6,7,4]

# min_custom(a,b,len(a))

# a = [3,4,5]

# b= [6,7,4]

# min_custom(a,b,len(a))

ne = [1, 2, 3, 4, 5, 6, 700, 800] # my 97, better than 99

min_custom(ne)

ne = [1, 50, 90, 100, 10000, 10001] # my 38, worth than 40

min_custom(ne)

ne = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # 1, the same

min_custom(ne)

ne = [1, 1, 2, 3, 29, 30, 210, 232, 12311, 12312] # abs(-19)= 19 , better than 21

min_custom(ne)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值