手机版
你好,游客 登录 注册
背景:
阅读新闻

Java算法面试-编程挑战题目

[日期:2014-06-01] 来源:Linux社区  作者:xiaofeilong [字体:大 中 小]

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));
 }
}

Java 8 中 HashMap 的性能提升 http://www.linuxidc.com/Linux/2014-04/100868.htm

Java 8 的 Nashorn 引擎 http://www.linuxidc.com/Linux/2014-03/98880.htm

Java 8简明教程 http://www.linuxidc.com/Linux/2014-03/98754.htm

本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-06/102553.htm

linux
相关资讯       算法  Java算法面试题 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款