1. 写一个算法实现在一个整数数组中,找出第二大的那个数字。
举例:int[ ] numbers = {1,3,5,0,6,9}; 输出:6
int[ ] numbers2 = {0,3,7,1,12,9}; 输出:9
int[ ] numbers = {66}; 输出:不存在
int[ ] numbers = {66,66,66,66,66}; 输出:不存在
public class Demo1 { public static void main(String[] args) { int[] a = {125,12,6,125,8,106,11,-13,0}; int second = getSecond(a); if (second == Integer.MIN_VALUE) System.out.println("第二大数字不存在!"); else System.out.println("第二大数字是:" + second); } public static int getSecond(int[] arr) { int first = arr[0]; int second = Integer.MIN_VALUE; for (int i = 1; i < arr.length; i++) { if (arr[i] > first) { second = first; first = arr[i]; } else if (arr[i] > second && arr[i] < first) { second = arr[i]; } } return second; } }
2. 写一个算法实现在一个整数数组中,把所有的0排到最后的位置。
import java.util.Arrays; public class Demo1 { public static void main(String[] args) { int[] a = { 0, 3, 7,0, 1,0, 12, 9 ,0,0}; pushZeroAtEnd(a); } public static void pushZeroAtEnd(int[] array) { int pos = array.length - 1; int start = 0; while (array[pos] == 0) { pos--; } while (start < pos) { if (array[start] == 0) { int t = array[pos]; array[pos] = array[start]; array[start] = t; while (array[pos] == 0) { pos--; } } start++; } System.out.println(Arrays.toString(array)); } }