当前位置:网站首页>【面试题】将一个无序整形数组的全部0移到末尾,并保持其它非0元素的相对顺序不变
【面试题】将一个无序整形数组的全部0移到末尾,并保持其它非0元素的相对顺序不变
2022-04-22 06:27:00 【三天打鱼,两天晒网】
问题描述: 将一个无序整形数组的全部0移到末尾,并保持其它非0元素的相对顺序不变。如:a={3,0,1,0,0,5,2,0,4,0},输出:{3,1,5,2,4,0,0,0,0,0}。
解决思路: 在Java中,一般数组是不可以直接增删元素的,可以转换成ArrayList再进行增删操作。而在Python中,可以将np.array数组转换成list,再进行增删操作。先逐个遍历数组元素,判断是否为0,为0则从ArrayList/list中移出,并用一个zero_list保存这些0,最后把两个列表合并。
Java代码如下:
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
int[] a = new int[]{3,0,1,0,0,5,2,0,4,0};
System.out.print("原数组:");
System.out.println(Arrays.toString(a));
a = moveZeroToEnd(a);
System.out.print("处理后的数组:");
System.out.println(Arrays.toString(a));
}
public static int[] moveZeroToEnd(int[] arr) {
// 将数组转换成list
List<Integer> arr_list = Arrays.stream(arr).boxed().collect(Collectors.toList());
List<Integer> zero_list = new ArrayList<>();
for(int i = 0; i < arr_list.size();) {
// 如果元素为0,则把它添加到zero,并把它从list中移出出来
if(arr_list.get(i) == 0) {
zero_list.add(0);
arr_list.remove(i);
}
else { //否则,跳过,再判断下一个元素
i++;
}
}
arr_list.addAll(zero_list); //合并两个list
// 将list转换成数组
int[] res = arr_list.stream().mapToInt(Integer::valueOf).toArray();
return res;
}
}
执行结果:
原数组:[3, 0, 1, 0, 0, 5, 2, 0, 4, 0]
处理后的数组:[3, 1, 5, 2, 4, 0, 0, 0, 0, 0]
Python代码如下:
import numpy as np
def move_zero_to_end(arr):
left_list = [] # 保存去掉0之后的list
zero_list = [] # 保存提取出来的全为0的list
for i in arr:
if i == 0:
zero_list.append(i)
else:
left_list.append(i)
return np.array(left_list + zero_list)
a = np.array([3,0,1,0,0,5,2,0,4,0])
print('原数组:')
print(a)
after_arr = move_zero_to_end(a)
print('处理后的数组:')
print(after_arr)
执行结果:
原数组:[3 0 1 0 0 5 2 0 4 0]
处理后的数组:[3 1 5 2 4 0 0 0 0 0]
注意:Python中的数组是通过np.array定义的,而直接定义a = [3,0,1,0,0,5,2,0,4,0]是list,而不是数组。
版权声明
本文为[三天打鱼,两天晒网]所创,转载请带上原文链接,感谢
https://blog.csdn.net/u014259820/article/details/100561320
边栏推荐
猜你喜欢

Learn the basic concepts of C language from scratch

C#自制一个简单的树莓派IP寻找工具

Thread pool usage

从零学C语言 【一】基本概念

Dependency conflict finding and resolution (taking easypoi as an example, nosuchmethoderror or NoClassDefFoundError appears)

@ transactional transaction propagation in the same class

QT动态翻译中英文语言

VC call control
![[communication interface can bus]](/img/71/e4285890a6c9298b79c00797afe595.png)
[communication interface can bus]

elmentUI 表格样式自定义(行颜色、背景色、内容滚动、去滚动条)
随机推荐
Unity ~ script life cycle
Multithreading (thread class, runnable interface, callable interface, synchronized, lock, thread pool)
Unity Update当前帧与上一帧鼠标的差值获取
【TCP/IP 一 概述】
C#中分支的使用
Use of branches in C #
Problem A: 人脸识别
循环详解和各种小细节
UML class diagram
[GPS - NMEA-0183 protocol]
观察者模式--ApplicationContext
可视化编程——如何自定义鼠标光标
redis监听key过期事件
多线程(Thread 类、Runnable 接口、Callable 接口、synchronized 、Lock、线程池)
Use of C variable and precautions
Unity读取excel 数据 并创建对应的json文件
UML类图
MFC常用格式轉換及函數
树莓派4:自定义网络时间来源
树莓派配置清单(入门参考)