2013-01-07 31 views
0
import java.util.Scanner; 

class main{ 
public static void main(String args[]){ 
    Scanner input = new Scanner(System.in); 
    int n,k,m=0; 
    n = input.nextInt(); 
    k = input.nextInt(); 
    for(int c = 0 ; c < n ; c++){ 
     if(input.nextInt() % k == 0) m++; 
    } 
    System.out.println(m); 
} 
} 

这是我对SPOJ Problem 442的解决方案。 我想知道如何让这段代码更快运行?什么是可以用来更快地创建java代码的技术?在java中减少程序运行时间 - 快速制作代码

+4

SO是用于编程问答。对于codereview,你最好在[Codereview](http://codereview.stackexchange.com/)上询问 –

+7

让这个程序更快的唯一方法就是更快地输入。除了等待超过99.99%的运行时间的用户输入之外,该程序不会做任何事情。 – jlordo

+0

你想在程序中做什么? –

回答

4

我的解决方案!

Scanner对于庞大的输入数据太慢。

你应该自己写一个简单的扫描仪,那么你会得到交流!

import java.io.BufferedInputStream; 
import java.io.IOException; 
import java.io.InputStream; 

public class Main { 

    static int nextInt(InputStream in) throws IOException { 
    int ch; 
    for (; (ch = in.read()) < '0' || ch > '9';); 
    int c = ch - '0'; 
    for (; (ch = in.read()) <= '9' && ch >= '0'; c = c * 10 + ch - '0'); 
    return c; 
    } 

    public static void main(String[] args) throws IOException { 

    InputStream in = new BufferedInputStream(System.in, 4096); 
    int n = nextInt(in); 
    int k = nextInt(in); 
    int t = 0; 
    for (int i = 0; i < n; i++) { 
     if (nextInt(in) % k == 0) t++; 
    } 
    System.out.println(t); 
    } 
} 
+0

设置缓冲区大小为4096会变得更快 – jackalope

+0

非常感谢!有效! –

+1

您在nextInt函数中的第一个“for”的条件应该如下:for(;(ch = in.read())< '0' || ch >'9';); –