- 想想你根本解决不了的情况
- 不对数组进行排序,而是构建 2 个每个大小为 6 的映射(构建和查找的时间为 O(N),查找时间为 O(1))+ 计算总和
- 然后对差异应用贪心算法以移动最大步长等,直到差异为零(再次 O(N) 复杂度)
总体复杂度为 O(N)
Python 代码:
def _cast_to_dict(A):
initial_dict = {i: 0 for i in range(1, 7)}
total_sum = 0
for a in A:
total_sum += a
initial_dict[a] += 1
return initial_dict, total_sum
def solution(A, B):
if len(A) > 6 * len(B) or len(B) > 6 * len(A):
# Case where the problem is not solvable
raise ValueError("Impossible to achieve")
state_of_A, sum_A = _cast_to_dict(A)
state_of_B, sum_B = _cast_to_dict(B)
total_moves = 0
if sum_A == sum_B:
return 0
elif sum_A < sum_B:
state_of_A, state_of_B = state_of_B, state_of_A
sum_A, sum_B = sum_B, sum_A
# Now we can assume sum_A > sum_B
# to reduce the diff, we can either increase B or decrease A
diff = sum_A - sum_B
print('DIFF %i' % diff)
possible_jumps = {5: [(6, 1)], 4:[(6, 2), (5, 1)], 3:[(6, 3), (5, 2), (4, 1)], 2:[(6, 4), (5, 3), (4, 2), (3, 1)], 1:[(6, 5), (5, 4), (4, 3), (3, 2), (2, 1)]}
while diff > 0:
max_diff_to_jump = min(5, diff)
for possible_jump in range(max_diff_to_jump, 0, -1):
is_jump_realized = False
print('Possible jump %i' % possible_jump)
for swap in possible_jumps[possible_jump]:
if state_of_A[swap[0]] > 0:
print('flipping A with (%s, %s)' % swap)
state_of_A[swap[0]] -= 1
state_of_A[swap[1]] += 1
diff -= possible_jump
total_moves += 1
is_jump_realized = True
break
elif state_of_B[swap[1]] > 0:
print('flipping B with (%s, %s).T' % swap)
state_of_B[swap[1]] -= 1
state_of_B[swap[0]] += 1
diff -= possible_jump
total_moves += 1
is_jump_realized = True
break
if is_jump_realized:
break
return total_moves