查找整数
问题描述
给出一个包含n个整数的数列,问整数a在数列中的第一次出现是第几个。
输入格式
第一行包含一个整数n。
第二行包含n个非负整数,为给定的数列,数列中的每个数都不大于10000。
第三行包含一个整数a,为待查找的数。
输出格式
如果a在数列中出现了,输出它第一次出现的位置(位置从1开始编号),否则输出-1。
样例输入
6
1 9 4 8 3 9
9
1 9 4 8 3 9
9
样例输出
2
数据规模与约定
1 <= n <= 1000。
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(buf.readLine());
String str = buf.readLine();
String s[] = str.split(" ");
String s1 = buf.readLine();
int x = Integer.parseInt(s1);
int a[] = new int [n];
for(int i=0; i<s.length; i++){
a[i] = Integer.parseInt(s[i]);
}
for(int j=0; j<s.length; j++){
if(j==s.length-1 && x!=a[s.length-1]){
System.out.println(-1);
break;
}
if(x==a[j]){
System.out.println(j+1);
break;
}
}
}
}
数列排序
问题描述
给定一个长度为n的数列,将这个数列按从小到大的顺序排列。1<=n<=200
输入格式
第一行为一个整数n。
第二行包含n个整数,为待排序的数,每个整数的绝对值小于10000。
第二行包含n个整数,为待排序的数,每个整数的绝对值小于10000。
输出格式
输出一行,按从小到大的顺序输出排序后的数列。
样例输入
5
8 3 6 4 9
8 3 6 4 9
样例输出
3 4 6 8 9
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args)throws Exception{
BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(buf.readLine());
String s=buf.readLine();
String s1[]=s.split(" ");
StringBuffer sB=new StringBuffer();
int a[]=new int[n];
for(int i=0;i<n;i++){
a[i]=Integer.parseInt(s1[i]);
}
java.util.Arrays.sort(a);
for(int j=0;j<n;j++)
sB.append(a[j]).append(" ");
System.out.println(sB);
}
}