字符串排序:
用Java编写一个能对一组字符串按字典序升序排序的程序 输入为N和N行字符串,需要按行输出字符串升序排序的结果
输入:3 Abc Abe Abd
输出:Abc Abd Abe
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int t = cin.nextInt();
List<String> lists = new ArrayList<String>();
for (int i = 0; i <= t; i++) {
lists.add(cin.nextLine());
}
Collections.sort(lists);
for (String li : lists) {
System.out.println(li);
}
}
}
斐波那契数列://迭代版的斐波那契才能全部通过 递归版本的只能得40分
import java.util.Scanner;
//迭代版本
public class Main {
public long fab(int n){
if(n==0||n==1)
return 1;
else{
long f1 =1l;
long f2 =1l;
long f3 =0l;
for(int i = 0; i < n-1;i++){
f3 = f1 + f2;
f1 = f2;
f2 = f3;
}
return f3;
}
}
public static void main(String args[]){
Scanner cin = new Scanner(System.in);
int num = cin.nextInt();
Main m =new Main();
System.out.println(m.fab(num));
}
}
交集
给定两个数组(数组中不包含相同元素),求两个数组的交集中元素的个数(即共同出现的数,如没有则输出为None) 如
输入:5
1 2 4 6 8
6
1 2 5 6 7 8
输出: 4
import java.util.Scanner;
public class Main{
public static void main(String args[]){
int num1 ,num2 ,times =0;
Scanner cin = new Scanner(System.in);
num1 = cin.nextInt();
int [] a1 = new int [num1];
for(int i = 0; i < a1.length; i++)
a1[i] = cin.nextInt();
num2 = cin.nextInt();
int [] a2 = new int [num2];
for(int i = 0; i < a2.length; i++)
a2[i]= cin.nextInt();
for(int i = 0; i < a1.length; i++)
for( int j = 0; j < a2.length; j++){
if(a1[i] == a2[j])
times+=1;
}
if(times>0)
System.out.println(times);
else
System.out.println("None");
}
}