数组递归练习:基于2的幂规模数组的差分计算实现
Alright, let's break down this problem into two clear parts and tackle each with practical, easy-to-follow code examples (using Python, since it's intuitive for this kind of task).
a) Non-inplace Solution (Creating New Arrays)
First, we need to make sure our initial array has a length that's a power of 2 (like 2, 4, 8, 16, etc.). The core idea is to repeatedly compute the difference of each pair of elements (0&1, 2&3, etc.), store those differences in a new array, and keep doing this until only one value remains.
How it works:
- Generate a random array of the specified power-of-2 size.
- Use a loop to create a new array each iteration, filled with pairwise differences from the current array.
- Stop when the array length is reduced to 1.
import random def get_final_difference_non_inplace(size): # Validate input: size must be a power of 2 if (size & (size - 1)) != 0: raise ValueError("Size must be a power of 2 (e.g., 2, 4, 8)") # Generate random integer array (values between 1-100 for readability) arr = [random.randint(1, 100) for _ in range(size)] print(f"Initial array: {arr}") current_arr = arr.copy() while len(current_arr) > 1: new_arr = [] # Iterate over pairs with step=2 to avoid index errors for i in range(0, len(current_arr), 2): # Calculate difference (adjust order if you need first - second instead) diff = current_arr[i+1] - current_arr[i] new_arr.append(diff) current_arr = new_arr print(f"Step result: {current_arr}") return current_arr[0] # Test with size=8 final_val = get_final_difference_non_inplace(8) print(f"Final remaining difference: {final_val}")
Key note on loop boundaries: Using range(0, len(current_arr), 2) ensures we only access valid pairs. Since we start with a power of 2, every iteration's array length stays even, so we never end up with an unpaired element.
b) Inplace Solution (No New Arrays)
The inplace version avoids creating new arrays entirely by overwriting the first half of the original array with pairwise differences each iteration. We track the "active" length of the array as we go.
How it works:
- Start with the same valid power-of-2 array.
- Use a variable to track the current active length of the array.
- For each iteration, compute pairwise differences and store them in the first half of the array, then halve the active length.
- Stop when the active length is 1.
import random def get_final_difference_inplace(size): if (size & (size - 1)) != 0: raise ValueError("Size must be a power of 2 (e.g., 2, 4, 8)") arr = [random.randint(1, 100) for _ in range(size)] print(f"Initial array: {arr}") current_length = size while current_length > 1: # We only need to fill the first half of the active array for i in range(current_length // 2): # Compute difference and store in position i arr[i] = arr[2*i + 1] - arr[2*i] # Halve the active length for the next iteration current_length = current_length // 2 print(f"Step result (first {current_length} elements active): {arr[:current_length]}") return arr[0] # Test with size=8 final_val = get_final_difference_inplace(8) print(f"Final remaining difference: {final_val}")
Key note on loop boundaries: Using range(current_length // 2) ensures we only compute the exact number of differences needed. The indices 2*i and 2*i+1 will never go out of bounds because 2*(current_length//2 - 1) + 1 = current_length - 1, which is the last valid index of the active array.
Quick Adjustments:
- If you need the difference to be
first element - second elementinstead, just swap the order in the subtraction line (e.g.,arr[i] = arr[2*i] - arr[2*i + 1]). - The input validation check
(size & (size -1)) == 0is a fast way to confirm a number is a power of 2.
内容的提问来源于stack exchange,提问作者noogler

