网站首页 网站地图
网站首页 > 娱乐人生 > 数组压缩编程题怎么做的

数组压缩编程题怎么做的

时间:2026-03-20 19:12:17

数组压缩编程题通常要求将一个数组中的连续重复元素替换为该元素及其出现次数的形式,并且要求压缩后的数组长度尽可能小。以下是几种常见的数组压缩方法:

方法一:插入排序算法

这种方法类似于插入排序,通过比较和插入操作将不重复的元素按顺序排列,重复的元素则记录其出现次数后替换。

```python

def compress_array(arr):

if not arr:

return 0

write_index = 0

for read_index in range(1, len(arr)):

if arr[read_index] != arr[read_index - 1]:

arr[write_index] = arr[read_index - 1]

write_index += 1

else:

count = 1

while read_index + 1 < len(arr) and arr[read_index] == arr[read_index + 1]:

read_index += 1

count += 1

arr[write_index] = str(count) + arr[read_index]

write_index += 1

read_index += 1

return write_index

```

方法二:双指针法

使用两个指针分别指向读和写的位置,读入连续的一串字符,然后将压缩版写到数组中。

```python

def compress_array(chars):

w, anchor = 0, 0

while w < len(chars):

r = anchor

while r + 1 < len(chars) and chars[r] == chars[r + 1]:

r += 1

chars[w] = chars[r]

w += 1

if r + 1 < len(chars):

num = str(r - anchor + 1)

for val in num:

chars[w] = val

w += 1

anchor = r + 1

return w

```

方法三:原地修改

这种方法不需要额外的空间,直接在输入数组上进行修改,并返回新的数组长度。

```python

def compress_array(chars):

if not chars:

return 0

write_index = 0

for read_index in range(len(chars)):

if read_index == 0 or chars[read_index] != chars[read_index - 1]:

chars[write_index] = chars[read_index]

write_index += 1

else:

count = 1

while read_index + 1 < len(chars) and chars[read_index] == chars[read_index + 1]:

read_index += 1

count += 1

chars[write_index] = str(count)

write_index += 1

read_index += 1

return write_index

```

注意事项

压缩后的长度必须小于或等于原数组长度,否则无法实现原地压缩。

处理连续重复元素时,需要记录其出现次数,并将其转换为字符串后替换。

双指针法可以避免额外的空间开销,适用于需要原地修改数组的情况。

示例

```python

chars = ['a', 'a', 'b', 'b', 'c', 'c', 'c']

new_length = compress_array(chars)

print(chars[:new_length]) 输出: ['a', '2', 'b', '2', 'c', '3']

```

通过以上方法,可以实现数组的压缩,并且确保压缩后的数组长度尽可能小。