用于排序数组中最后一个重复元素的Python程序
我们有一个带有重复元素的排序数组,我们必须找到最后一个重复元素的索引并打印它的索引并打印重复元素。如果没有找到这样的元素,则打印一条消息。
例子:
Input : arr[] = {1, 5, 5, 6, 6, 7}
Output :
Last index: 4
Last duplicate item: 6
Input : arr[] = {1, 2, 3, 4, 5}
Output : No duplicate found
我们只需以相反的顺序遍历数组并比较当前元素和前一个元素。如果找到匹配项,则打印索引和重复元素。由于这是已排序的数组,因此它将是最后一个副本。如果没有找到这样的元素,我们将为它打印消息。
1- for i = n-1 to 0
if (arr[i] == arr[i-1])
Print current element and its index.
Return
2- If no such element found print a message
of no duplicate found.
Python3
# Python3 code to print last duplicate
# element and its index in a sorted array
def dupLastIndex(arr, n):
# if array is null or size is less
# than equal to 0 return
if (arr == None or n <= 0):
return
# compare elements and return last
# duplicate and its index
for i in range(n - 1, 0, -1):
if (arr[i] == arr[i - 1]):
print("Last index:", i, "
Last",
"duplicate item:",arr[i])
return
# If we reach here, then no duplicate
# found.
print("no duplicate found")
arr = [1, 5, 5, 6, 6, 7, 9]
n = len(arr)
dupLastIndex(arr, n)
# This code is contributed by
# Smitha Dinesh Semwal
输出:
Last index: 4
Last duplicate item: 6
有关详细信息,请参阅有关排序数组中最后一个重复元素的完整文章!