移动数组中所有的0到数组最后(2018携程笔试题)

题目要求:把数组中所有的0移动到数组的最后,不改变非零元素的相对位置。

例如
输入: {4, 5 ,0 ,3 ,0,7}
输出: {4, 5 ,3, 7 ,0,0}

代码如下,主函数处理输入,moveZerosFromArray()才是处理函数,代码很简洁:

package xiecheng;

import java.util.ArrayList;
import java.util.Scanner;

public class MoveZerosFromArray {
	public static void main(String[] args) {
		
		/*
		 * 这是处理只有一行,最后存入数组的情况!
		 * 
		 */
		//第一步:这一部分是处理输入的,从命令行读取一行,输出这一行转成的数组a
        ArrayList<Integer> arrl = new ArrayList<Integer>();  //使用链表存储不定长的数据,最后转成数组
		Scanner in = new Scanner(System.in);
		String s = in.nextLine();   //读取一行输入
		String[] s1 = s.split(" ");  //按空格分割字符串,得到字符串数组
		
		for(String s2 : s1) {   //把字符串数组转成Integer存入
			arrl.add(Integer.valueOf(s2));
		}
		Integer[] d = arrl.toArray(new Integer[arrl.size()]);  //把链表转成数组
		int[] a = new int[d.length];  
		for(int i = 0; i < a.length; i++){  //把Integer转成int
		    a[i] = d[i];
		}  
		
		
		//第二步:调用函数,返回结果
		int[] result = moveZerosFromArray(a);
		
		//第三步:打印函数后的处理结果
		for(int j = 0; j < result.length; j++) {  //打印最后结果
			System.out.print(result[j] + " ");
		}
	}
	
    //把数组所有的0移到最后
	public static int[] moveZerosFromArray(int[] a) {
		int begin = 0;
		int end = 0;
		for (int i = 0; i < a.length; i++) {
			if (a[i] == 0) { // 当前位是0
				for (int j = i + 1; j < a.length; j++) {  //遍历后面的元素
					if (a[j] != 0) { // 找出0后面的第一个不是0的元素
						int temp = 0;  //交换这两个元素
						temp = a[i];
						a[i] = a[j];
						a[j] = temp;
						break;
					}
				}
			}
		}
		return a;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值