Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Java算法面试-编程挑战题目

1. 写一个算法实现在一个整数数组中,找出第二大的那个数字。举例:int[ ] numbers = {1,3,5,0,6,9}; 输出:6int[ ] numbers2 = {0,3,7,1,12,9}; 输出:9int[ ] 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));
 }
}Java 8 中 HashMap 的性能提升 http://www.linuxidc.com/Linux/2014-04/100868.htmJava 8 的 Nashorn 引擎 http://www.linuxidc.com/Linux/2014-03/98880.htmJava 8简明教程 http://www.linuxidc.com/Linux/2014-03/98754.htm本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-06/102553.htm