Skip to content

Commit 461c909

Browse files
authored
solved list index out of range
python代码 flag = array[left] > array[right] 没有判断 left 和 right 的大小,可能会越界。 例: [6, 8, 7, 4, 5, 3, 2, 1]
1 parent 67819d2 commit 461c909

File tree

1 file changed

+4
-1
lines changed
  • zh-hans/basics_data_structure

1 file changed

+4
-1
lines changed

zh-hans/basics_data_structure/heap.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,10 @@ class MaxHeap:
4242
left, right = 2 * i + 1, 2 * i + 2
4343
max_index = i
4444
# should compare two chidren then determine which one to swap with
45-
flag = array[left] > array[right]
45+
if left < len(array) and right < len(array):
46+
flag = array[left] > array[right]
47+
else:
48+
flag = True
4649
if left < len(array) and array[left] > array[max_index] and flag:
4750
max_index = left
4851
if right < len(array) and array[right] > array[max_index] and not flag:

0 commit comments

Comments
 (0)