首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更有效地从控制台读取int值

更有效地从控制台读取int值
EN

Stack Overflow用户
提问于 2019-01-23 09:00:39
回答 3查看 75关注 0票数 0

如何更有效地(从内存中)从控制台读取int值:

代码语言:javascript
复制
BufferedReader in ...
number = Integer.parseInt(in.readLine());

当我使用readLine()并将其解析为int时,java会创建许多字符串对象,而с则会占用内存。我尝试使用ScannernextInt()方法,但这种方法也没有那么有效。

我需要读> 1000_000值,并且我有内存限制。

编辑全部任务代码

代码语言:javascript
复制
import java.io.*;

public class Duplicate {

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

        int last = 0;
        boolean b = false;

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(reader.readLine());

        for (int i = 0; i < n; i++) {
            int number =Integer.parseInt(reader.readLine());
            if (number == 0 && !b) {
                System.out.println(0);
                b = true;
            }
            if (number == last) continue;
            last = number;
            System.out.print(last);
        }
    }
}

重写变体:

代码语言:javascript
复制
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

public class Duplicate {

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

        int last = 0;
        boolean b = false;

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        int nextInt = getNextInt(reader);

        for (int i = 0; i < nextInt; i++) {
            int number = getNextInt(reader);
            if (number == 0 && !b) {
                System.out.println(0);
                b = true;
            }
            if (number == last) continue;
            b = true;
            last = number;
            System.out.println(last);
        }
    }

    static int getNextInt(Reader in) throws IOException {
        int c;
        boolean negative = false;
        do {
            c = in.read();
            if (!Character.isDigit(c)) {
                negative = c == '-';
            }
        } while (c != -1 && !Character.isDigit(c));
        if (c == -1) return Integer.MIN_VALUE;

        int num = Character.getNumericValue(c);
        while ((c = in.read()) != -1 && Character.isDigit(c)) {
            num = 10 * num + Character.getNumericValue(c);
        }
        return negative ? -num : num;
    }
}

这两个选项都不会从内存中传递())

EDIT2 I尝试分析

int number = getRandom();并从1000000开始

再一次发射

并溅出GC

EN

回答 3

Stack Overflow用户

发布于 2019-01-23 09:15:32

您可以一次从in中读取一个字符,检查它是否是一个数字,然后将其累加到一个数字中。类似于:

代码语言:javascript
复制
int getNextInt(Reader in) throws IOException {
  int c;
  boolean negative = false;
  do {
    c = in.read();
    if (!Character.isDigit(c)) { negative = c == '-' };
  } while (c != -1 && !Character.isDigit(c));
  if (c == -1) return Integer.MIN_VALUE;  // Some sentinel to indicate nothing found.

  int num = Character.getNumericValue(c);
  while ((c = in.read()) != -1 && Character.isDigit(c)) {
    num = 10 * num + Character.getNumericValue(c);
  }
  return negative ? -num : num;
}

Ideone演示

当然,这是难以置信的原始解析。但是,您也许可以将此代码作为基础,并根据需要对其进行调整。

票数 1
EN

Stack Overflow用户

发布于 2019-01-23 09:12:52

您可以使用这个FastScanner

代码语言:javascript
复制
static class FastScanner {
    private BufferedReader reader = null;
    private StringTokenizer tokenizer = null;

    public FastScanner(InputStream in) {
        reader = new BufferedReader(new InputStreamReader(in));
        tokenizer = null;
    }

    public String next() {
        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenizer.nextToken();
    }

    public String nextLine() {
        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                return reader.readLine();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return tokenizer.nextToken("\n");
    }

    public long nextLong() {
        return Long.parseLong(next());
    }

    public int nextInt() {
        return Integer.parseInt(next());
    }
}

codeforces上非常常用的方法是读取Scanner类导致TLE的大输入。

这最初是由https://codeforces.com/profile/Petr编写的

票数 0
EN

Stack Overflow用户

发布于 2019-01-23 14:33:02

我在codeforces上使用这个codeforces。对我来说,在大型输入情况下效果很好。您可以将其扩展到您的用例。在获得使用TLEScanner并在需要时添加功能之后,我发现了这一点。

代码语言:javascript
复制
static class InputReader {
    private final InputStream stream;
    private final byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    private int read() {
        try {
            if (curChar >= numChars) {
                curChar = 0;
                numChars = stream.read(buf);
                if (numChars <= 0)
                    return -1;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return buf[curChar++];
    }

    public int readInt() {
        return (int) readLong();
    }

    public long readLong() {
        int c = read();
        while (isSpaceChar(c)) {
            c = read();
            if (c == -1) throw new RuntimeException();
        }
        boolean negative = false;
        if (c == '-') {
            negative = true;
            c = read();
        }
        long res = 0;
        do {
            if (c < '0' || c > '9') throw new InputMismatchException();
            res *= 10;
            res += (c - '0');
            c = read();
        } while (!isSpaceChar(c));
        return negative ? (-res) : (res);
    }

    public int[] readIntArray(int size) {
        int[] arr = new int[size];
        for (int i = 0; i < size; i++) arr[i] = readInt();
        return arr;
    }

    private boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54323425

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档