如何将数组中某元素移至另一元素前方(不交换二者位置)
How to Move an Array Element Before Another Element (No Swapping)
Alright, let's break this down clearly: you want to take one element from an array and relocate it directly in front of another specified element—no swapping involved, meaning the destination element stays in its relative order with the rest of the array (only the moved element changes position).
Core Approach
The process follows 4 straightforward steps:
- Find the index of the element you want to move (let's call this
target). - Find the index of the element you want the
targetto sit before (let's call thisdestination). - Remove the
targetfrom its original position in the array. - Insert the
targetat the index of thedestinationelement—this shifts thedestinationand all elements after it one spot to the right, placing thetargetexactly where you want it.
Example Implementations
Let's use your sample arrays to demonstrate with two common programming languages.
Python Example
def move_element_before(arr, target_val, dest_val): try: target_idx = arr.index(target_val) dest_idx = arr.index(dest_val) except ValueError: # Handle case where either element isn't in the array return arr.copy() # Make a copy to avoid modifying the original array (safe practice) new_arr = arr.copy() # Remove the target element removed_target = new_arr.pop(target_idx) # Adjust destination index if target was originally before it (since we popped an element left of it) if target_idx < dest_idx: dest_idx -= 1 # Insert target right before the destination element new_arr.insert(dest_idx, removed_target) return new_arr # Test your examples original = [5,7,3,6,4] # Move 3 before 5 result1 = move_element_before(original, 3, 5) print(result1) # Output: [3,5,7,6,4] # Move 6 before 7 (using result1 as input) result2 = move_element_before(result1, 6, 7) print(result2) # Output: [3,5,6,7,4] # Move 4 before 5 (using result2 as input) result3 = move_element_before(result2, 4, 5) print(result3) # Output: [3,4,5,6,7]
JavaScript Example
function moveElementBefore(arr, targetVal, destVal) { const targetIdx = arr.indexOf(targetVal); const destIdx = arr.indexOf(destVal); if (targetIdx === -1 || destIdx === -1) { // Return a copy if either element isn't found return [...arr]; } // Create a copy to avoid mutating the original array const newArr = [...arr]; // Remove target from its original position newArr.splice(targetIdx, 1); // Adjust destination index if target was before it const adjustedDestIdx = targetIdx < destIdx ? destIdx - 1 : destIdx; // Insert target right before the destination element newArr.splice(adjustedDestIdx, 0, targetVal); return newArr; } // Test your examples let original = [5,7,3,6,4]; // Move 3 before 5 let result1 = moveElementBefore(original, 3, 5); console.log(result1); // Output: [3,5,7,6,4] // Move 6 before 7 let result2 = moveElementBefore(result1, 6, 7); console.log(result2); // Output: [3,5,6,7,4] // Move 4 before 5 let result3 = moveElementBefore(result2, 4, 5); console.log(result3); // Output: [3,4,5,6,7]
Key Notes
- We create copies of the original array to avoid modifying it directly—this is a best practice unless you explicitly want to mutate the original.
- We adjust the destination index if the target was originally before it: when we remove the target, all elements after it shift left by one, so the destination's index decreases by 1 in that scenario.
- The code includes checks for cases where either the target or destination element isn't present in the array, returning a copy of the original array in those cases.
内容的提问来源于stack exchange,提问作者Anurag Dhadse
相关产品推荐
相关产品推荐

