2015-05-01 38 views
-3

我得到了字符串中最大的数字和最小的数字。但是,如何从这个问题中找到此Java代码中的第二大数字和第三大数字?我应该使用哪些代码?请解释这个java代码中的第一大和第二大?

public class Problem1 
{ 
public static void main(String[] args) { 
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 
// int b[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; 
Problem1 app = new Problem1(); 
app.scrambleArray(a); 
app.print(a); 
// Usage enable assertions: -ea to VM arguments 
int result = app.findInt(a, 10); 
assert (result == 10) : 
String.format("Expected <10> but was <%d>", result); 
result = app.findInt(a, 11); 
assert (result == -1) : 
String.format("Expected <-1> but was <%d>", result); 
System.out.printf("Largest Number is : %d%n", app.getMax(a)); 
app.print(app.reverseArray(a)); 
} 
public void scrambleArray(int[] a) { 
for (int i = 0; i < a.length; i++) { 
int pos = new Random().nextInt(a.length); 
int tmp = a[i]; 
a[i] = a[pos]; 
a[pos] = tmp; 
} 
} 
public void print(int[] a) { 
System.out.println(Arrays.toString(a)); 
} 
public int getMax(int[] a) { 
int max = a[0]; 
for (int i = 1; i < a.length; i++) { 
max = Math.max(a[i], max); 
} 
return max; 
} 
public int findInt(int[] a, int value) { 
int result = -1; 
for (int i : a) { 
if (value == i) { 
result = value; 
break; 
} 
} 
return result; 
} 
public int[] reverseArray(int[] a) { 
int[] results = new int[a.length]; 
for (int i = 0, idx = a.length - 1; i < a.length; i++, idx--) { 
results[i] = a[idx]; 
} 
return results; 
} 
} 
+0

排序的阵列,最后一个值是larget,倒数第二是第二大和等 – underdog

+0

我如何分类? – Stranger1

回答

1

使用Arrays.sort()方法进行排序的整数数组

int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 
Arrays.sort(a); 
System.out.println("largest value: " + a[a.length - 1]); 
System.out.println("second largest: " + a[a.length - 2]); 
+0

非常感谢。我知道了!!!干杯 – Stranger1

0

prior answer通常是一个很好的解决方案。例外是如果数组中的元素数量非常大并且性能很重要。在这种情况下,它可能会更快地保持在一个有序集合N个最大的元素,并避免排序整个名单:

public int[] getNLargest(int[] in, int n){ 
    TreeSet<Integer> large = new TreeSet<Integer>(); 
    for(int i : in){ 
     if(large.size() < n){ 
     large.add(i); 
     } else if(i > large.first().intValue()){ 
     large.remove(large.first()); 
     large.add(i); 
     } 
    } 
    int[] result = new int[large.size()]; 
    int index = 0; 
    for(Integer i : large){ 
     result[index] = i.intValue(); 
     index++; 
    } 
    return result; 
    } 
相关问题