最后推零 [英] Push zeroes at the end

查看:63
本文介绍了最后推零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个随机整数数组,将所有存在的零推送到数组的末尾。其他元素的相应顺序应保持不变。

更改输入数组本身。您无需返回或打印元素。不要使用额外的数组。

注意:你需要在一次扫描数组中这样做。

输入格式:



我尝试过:



  public   class  PushZerosAtEnd {

public static void pushZerosAtEnd( int [] arr){
int [] temp = new int [arr.length];
int i = 0 ;
int k = 0 ;
while (i< arr.length&& k< temp.length){
if (arr [i]!= 0 ){
temp [k] = arr [i];
i ++;
k ++;
}
else {
i ++;
}
}
for int l = 0 ; l< arr.length; l ++){
System.out.print(arr [l] + );
}

}
}





我不知道为什么会这样返回,而调试很好

解决方案

这将是我的算法:

  for  每个 n    array 
如果 数组 [n]为零,则
移动所有项目 数组在n前进
后设置最后一项 array 为零 // (即数组) [last] = 0)
endif
endfor

函数memmove对于移动内存块很方便。


< blockquote class =quote>

引用:

我不知道为什么这个返回,而调试很好



这是不可能的,你无法得到正确的结果,因为代码是错误的。

重读你的代码和注意你用 temp 做什么。



你的要求说:

Quote:

更改输入数组本身。您无需返回或打印元素。不要使用额外的数组。



但你使用的是新数组 temp 。尝试相应地更改代码,这并不是很复杂。


Given a random integer array, push all the zeros that are present to end of the array. The respective order of other elements should remain same.
Change in the input array itself. You don't need to return or print elements. Don't use extra array.
Note : You need to do this in one scan of array only.
Input format :

What I have tried:

public class PushZerosAtEnd {
	
	public static void pushZerosAtEnd(int[] arr){
              int [] temp= new int[arr.length];
		      int i=0;
		      int k=0;
		      while(i<arr.length && k<temp.length){
		        if(arr[i]!=0){
		          temp[k]=arr[i];
		          i++;
		          k++;
		        }
		        else{
		          i++;
		        }
		      }
      for(int l=0;l<arr.length;l++){
       System.out.print(arr[l] + " ");
	}

	}
}



I don't know why is this returning the, whereas debugging is good

解决方案

This would be my algorithm :

for each n in array :
   if array[n] is zero then
      move all items in array after n forward
      set last item in array to zero  //(ie., array[last] = 0)
   endif
endfor

The function memmove is handy for moving blocks of memory.


Quote:

I don't know why is this returning the, whereas debugging is good


That is impossible, you can't get a correct result because the code is wrong.
Reread your code and pay attention to what you do with temp.

Your requirement say:

Quote:

Change in the input array itself. You don't need to return or print elements. Don't use extra array.


but you are using a new array temp. Try to change your code accordingly, it is not really complicated.


这篇关于最后推零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆