歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java算法面試-編程挑戰題目

Java算法面試-編程挑戰題目

日期:2017/3/1 9:43:42   编辑:Linux編程

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

Copyright © Linux教程網 All Rights Reserved