我们需要实现一个程序,实现输入数组后将数组中的最大值与第一个元素交换,最小值与最后一个元素交换,然后输出数组。这可以通过遍历数组来找到最大值和最小值,并进行交换来实现。
解题思路:
代码:
def swap_max_and_min(arr):
if not arr:
return arr
# Find the index of the maximum and minimum elements
max_idx = arr.index(max(arr))
min_idx = arr.index(min(arr))
# Swap the maximum with the first element and minimum with the last element
arr[0], arr[max_idx] = arr[max_idx], arr[0]
arr[-1], arr[min_idx] = arr[min_idx], arr[-1]
return arr
# Test the function
arr = [3, 1, 5, 8, 2, 4]
print("Original array:", arr)
result = swap_max_and_min(arr)
print("Array after swapping max and min:", result)
优点:
缺点:
解题思路:
代码:
def swap_max_and_min(arr):
if not arr:
return arr
max_val = float('-inf')
min_val = float('inf')
max_idx = None
min_idx = None
# Find the maximum and minimum elements and their indices
for i in range(len(arr)):
if arr[i] > max_val:
max_val = arr[i]
max_idx = i
if arr[i] < min_val:
min_val = arr[i]
min_idx = i
# Swap the maximum with the first element and minimum with the last element
arr[0], arr[max_idx] = arr[max_idx], arr[0]
arr[-1], arr[min_idx] = arr[min_idx], arr[-1]
return arr
# Test the function
arr = [3, 1, 5, 8, 2, 4]
print("Original array:", arr)
result = swap_max_and_min(arr)
print("Array after swapping max and min:", result)
优点:
缺点:
解题思路:
代码:
def swap_max_and_min(arr):
if not arr:
return arr
sorted_arr = sorted(arr)
max_val = sorted_arr[-1]
min_val = sorted_arr[0]
max_idx = arr.index(max_val)
min_idx = arr.index(min_val)
# Swap the maximum with the first element and minimum with the last element
arr[0], arr[max_idx] = arr[max_idx], arr[0]
arr[-1], arr[min_idx] = arr[min_idx], arr[-1]
return arr
# Test the function
arr = [3, 1, 5, 8, 2, 4]
print("Original array:", arr)
result = swap_max_and_min(arr)
print("Array after swapping max and min:", result)
优点:
缺点:
综上所述,推荐使用一次遍历查找并交换的方法(方法二)实现数组中的最大值与第一个元素交换,最小值与最后一个元素交换。