【最高效率解法】:
因为数组里的数组不会大于n , 故不会有数组下标越界问题,又因为题目中说只要找出重复的即可,所以对找出数字的先后顺序无要求。
public static int gaoXiaoMethod( int[] numbers ){
int intLength = numbers.length;
boolean[] b = new boolean[intLength];
for (int i = 0; i < intLength; i++) {
if ( b[ numbers[i] ] == false ){
b[ numbers[i] ]= true;
}else {
return numbers[i];
}
}
return -1;
}
【之前的解题思路】:
import java.util.Scanner;
public class 数组中的重复数字 {
public static void main(String[] args) {
int[] intsArray = {1, 55,2, 3, 2, 4, 55};
int num = duplicate(intsArray);
System.out.println(num);
}
public static int duplicate(int[] numbers) {
boolean flag = false;
boolean[] booArray = new boolean[numbers.length];
for (int i = 0; i < numbers.length; i++) {
int intLinShiNum = numbers[i];
int count = 0;
for (int j = i; j < numbers.length; j++) {
if (intLinShiNum == numbers[j]) {
count++;
}
}
if (count > 1) {
booArray[i] = true;
}
}
for (int i = 0; i < numbers.length; i++) {
if (booArray[i] == true) {
return numbers[i];
}
}
return -1;
}
}
【美丽的误解】:
一开始读题的时候,以为是要输入一个数组,多写了一些,没想到还没通过测试~ ~ ~ scanner.next(); //以 空格/回车 作为结束( 开头,结尾的空格都不能拿到 )。 scanner.nextLine(); //以回车作为结束,获取一整行。
import java.util.Scanner;
public class 数组中括号输入 {
public static void main(String[] args) {
quchu();
}
public static void quchu(){
System.out.println("请输入几个数并用逗号隔开:");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine().toString();
String str6 = str.trim();
int start = str6.indexOf("[");
int end = str6.lastIndexOf("]");
String allStr="";
try{
allStr = str6.substring(start+1, end);
}catch (StringIndexOutOfBoundsException e){
System.out.println(e.getMessage());
}
String[] arr = allStr.split(",");
int[] b = new int[arr.length];
for( int j = 0 ; j<b.length ; j++ ) {
String strj = arr[j].trim();
b[j] = Integer.parseInt( strj );
}
boolean[] booArray =new boolean[b.length];
for (int i = 0; i < b.length; i++) {
int intLinShiNum = b[i];
int count =0 ;
for (int j = i; j < b.length; j++) {
if (intLinShiNum == b[j]){
count++;
}
}
if (count>1){
booArray[i] = true;
}
}
for (int i = 0; i < b.length; i++) {
if (booArray[i]==true){
System.out.println(b[i]);
break;
}
}
}
}
|