acm用java怎么写_用java来写ACM
前言
從去年10月份開始就一直都在九度oj平臺寫acm,到今天在九度oj的總排名已經到了第6名,收獲很多特別是算法和數據結構方面的提高,這種提高直接反映在我找工作的順利中
但是人總要學會擁抱變化,特別是我即將加入阿里系,使用java編程,不能繼續貪戀用c的快感,盡快調節自己。因此從今天開始我要轉換自己的acm平臺,開始使用
LeetCode OJ
有點跑題,畢竟這篇博客還是偏向技術一些,不搞心靈雞湯類似的東西,因此這里主要講一下在寫ACM時如何快速的從c到java實現轉變
基本輸入輸出
其實我感覺在有c基礎后,學習java還是挺簡單的,寫acm時候主要是不太適應java的輸入輸出,其實關鍵還是在于你心里是否接受java的語法(吐槽:java的api的名字太TM長了吧)
在c里輸入輸出的標準格式:
#include
int main(void)
{
int a, b;
while (scanf("%d %d", &a, &b) != EOF) {
printf("%d\n", a + b);
}
return 0;
}
在java里提供了Scanner類可以方便我們跟c一樣進行輸入輸出:
import java.util.*;
public class IOclass {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int a, b;
while (cin.hasNext()) {
a = cin.nextInt();
b = cin.nextInt();
System.out.printf("%d\n", a + b);
}
}
}
API對比(java vs c):
讀一個整數 ?int a = cin.nextInt(); 相當于 scanf("%d", &a);
讀一個字符串 String s = cin.next(); 相當于 scanf("%s", s);
讀一個浮點數 double t = cin.nextDouble(); 相當于 scanf("%lf", t);
讀取整行數據 String s = cin.nextLine() 相當于 gets(s);
判斷是否有下一個輸出 while (cin.hasNext) 相當于 while (scanf("%d", &n) != EOF)
輸出 System.out.printf(); 相當于 printf();
方法調用
在java主類中main方法必須是public static void的,在main中調用非static方法時會報出錯誤,因此需要先建立對象,然后調用對象的方法
題目
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
代碼
import java.util.*;
public class SingleNumber {
public static void main(String[] args) {
int n, key, A[] = new int[1000];
Scanner cin = new Scanner(System.in);
while (cin.hasNext()) {
// 接收數組A
n = cin.nextInt();
for (int i = 0; i < n; i ++) {
A[i] = cin.nextInt();
}
// 調用方法
SingleNumber sn = new SingleNumber();
key = sn.singleNumber(A, n);
System.out.println(key);
}
}
public int singleNumber(int[] A, int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
for (int i = 1; i < A.length; i++) {
A[0] ^= A[i];
}
return A[0];
}
}
總結
以上是生活随笔為你收集整理的acm用java怎么写_用java来写ACM的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php替换算法,PHP实现各种经典算法
- 下一篇: 德州计算机速成班培训,德州办公软件培训速