1. 写一个算法实现在一个整数数组中,找出第二大的那个数字
举例:
int[ ] numbers = {1,3,5,0,6,9}; 输出:6
int[ ] numbers2 = {0,3,7,1,12,9}; 输出:9
参考答案:
public class SecondLargest
{
public static void main(String[] args)
{
SecondLargest sl = new SecondLargest();
int arr[] = {125,12,6,125,8,106,11,-13,0};
sl.findSecondLargest(arr);
}
public void findSecondLargest(int []arr)
{
if(arr.length < 1)
System.out.println(“List is empty”);
else
{
int slarge ;
int large = slarge = arr[0];
for(int i = 1; i<arr.length ; i++)
{
if(arr[i] == large)
{
}
else if(arr[i] > large)
{
slarge = large;
large = arr[i];
}
else if(arr[i]>slarge || large == slarge)
slarge = arr[i];
}
System.out.println(“Second heighest number is : “+slarge);
}
}
}
2. 写一个算法实现在一个整数数组中,把所有的0排到最后的位置。
参考答案:
public static void pushZeroAtEnd(int[] array) {
int pos = array.length – 1;
int start = 0;
while(array[pos] == 0)
{
pos–;
}
while(start < pos) {
//System.out.println(“Start = ” + start + “, array[start] = ” + array[start]);
if(array[start] == 0) {
//Swap
int t = array[pos];
array[pos] = array[start];
array[start] = t;
while(array[pos] == 0) {
pos–;
}
//printArray(array);
}
start++;
}
printArray(array);
}