题目:有一个n个正整数的数组a[0, n-1]作为输入,同时生成一个大小与a相同的数组array,然后处理a中的每个元素,如果当前的a[i]是奇数则直接添加到array中的最后一个元素后面,如果是偶数则从array中最后一个元素开始,向前依次删除所有奇数。我写了下面个程序,不知道为什么无法实现,希望大牛帮忙看下,为什么我这样调用无法实现功能...谢谢
package algorithm;public class TestAlgorithm {
int n = 7;
public static void main(String[] args) {
TestAlgorithm test = new TestAlgorithm();
int demo[] = {2, 3, 6, 4, 1, 7, 8};
test.function(demo);
for(int i = 0; i < demo.length; i++){
System.out.print(demo[i] + "\t");
}
}
public void function(int[] a){
int[] store = new int[n];
int j = 0;
for(int i = 0; i < a.length; i++){
if(a[i] % 2 == 0) //a[i]是偶数
while(j > 0 && store[j - 1] % 2 != 0)
store[j--] = 0; //删除前面的奇数
store[j++] = a[i];
}
return;
}
}
package algorithm;public class TestAlgorithm {
int n = 7;
public static void main(String[] args) {
TestAlgorithm test = new TestAlgorithm();
int demo[] = {2, 3, 6, 4, 1, 7, 8};
test.function(demo);
for(int i = 0; i < demo.length; i++){
System.out.print(demo[i] + "\t");
}
}
public void function(int[] a){
int[] store = new int[n];
int j = 0;
for(int i = 0; i < a.length; i++){
if(a[i] % 2 == 0) //a[i]是偶数
while(j > 0 && store[j - 1] % 2 != 0)
store[j--] = 0; //删除前面的奇数
store[j++] = a[i];
}
return;
}
}
解决方案 »
- 如何获得sq查询l结果的每个元素?
- 继承问题
- 请问关于java程序调用c语言程序的几种方法??
- 学着学着,就迷糊了!!请高手指点方向。。
- 如何将一个Frame中的Statement对象传递给另一个?
- MessageDigest.getInstance("MD5") 有几种参数?
- 一个让我头痛了好久的关于网络、多线程及I/0的问题,哪位帮忙看看~
- 新手们快进来,不然别后悔!!
- 看原代码FileSystem.java时看到奇怪(小弟太菜,只能用"奇怪")的static的用法,请大家帮忙解释一下,谢谢!
- 给点概念就好,1:用java能不能启动系统中的其它文件;2:用java能不能,如何实现多进程间的通信?谢谢各位高人
- check out 项目后不能建文件
- 关于java的classpath问题
不妨将function的void 改为 int[],然后return store。
调用的地方改为 int[] result = test.function(demo);下面去print result数组。
算法没细看。
int n = 7; public static void main(String[] args) {
TestAlgorithm test = new TestAlgorithm ();
int demo[] = { 2, 3, 6, 4, 1, 7, 8 };
int[] r = test.function(demo);
for (int i = 0; i < r.length; i++) {
System.out.print(r[i] + "\t");
}
} public int[] function(int[] a) {
int[] store = new int[n];
int j = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] % 2 == 0) // a[i]是偶数
while (j > 0 && store[j - 1] % 2 != 0)
store[j--] = 0; // 删除前面的奇数
store[j++] = a[i];
}
return store;
}
}我让你改成这样,再看。
如果用static修饰,就可以,前提是参数不用传,用整个类的静态变量。