You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数组重排任务:移除指定元素后将剩余元素右移并在左侧空位填充1

Solution to Array Manipulation Problem

Here's a straightforward, efficient approach to solve this problem, along with a Python implementation that aligns perfectly with the requirements:

Approach

For each test case, we follow three core steps:

  • Filter out target elements: Remove all instances of the value X from the array while keeping the original order of the remaining elements.
  • Calculate fill requirement: Figure out how many 1s we need to add to the left by subtracting the length of the filtered array from the original array size N.
  • Build the final array: Create the result by prepending the required number of 1s to the filtered array—this automatically shifts the remaining elements to the right and fills the left vacancies as specified.

Python Implementation

def process_array(n, arr, x):
    # Keep elements that are not equal to X
    filtered_elements = [num for num in arr if num != x]
    # Number of 1s needed is original length minus filtered length
    num_fill_ones = n - len(filtered_elements)
    # Combine 1s and filtered elements
    return [1] * num_fill_ones + filtered_elements

# Handle input and output
test_case_count = int(input())
output = []
for _ in range(test_case_count):
    array_size = int(input())
    input_array = list(map(int, input().split()))
    target_value = int(input())
    result = process_array(array_size, input_array, target_value)
    output.extend(map(str, result))

# Print combined results as space-separated string
print(' '.join(output))

Verification with Sample Input

Let’s walk through the sample input to confirm the output:

  1. First test case:
    • Original array: [22, 1, 34, 22, 16], target X=22
    • Filtered elements: [1, 34, 16]
    • Number of 1s needed: 5 - 3 = 2
    • Result: [1, 1, 1, 34, 16]
  2. Second test case:
    • Original array: [3,5,3,5,5,11,5], target X=5
    • Filtered elements: [3,3,11]
    • Number of 1s needed: 7 -3 =4
    • Result: [1,1,1,1,3,3,11]

Combining these gives the sample output: 1 1 1 34 16 1 1 1 1 3 3 11

This solution runs in O(N) time per test case, making it efficient even for larger arrays since we only iterate through the input array once for filtering.

内容的提问来源于stack exchange,提问作者Shrishti Kumari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 04:52:46