题目
除了最高和最低元素(值,而不是索引!)之外,对数组的所有数字求和(在F#和Haskell中得到一个列表)。
(最高/最低元素在每个边缘分别只有一个元素,即使有多个元素具有相同的值!)
示例:
{ 6, 2, 1, 8, 10 } => 16
{ 1, 1, 11, 2, 3 } => 6
如果array为空,null或None,或者如果只存在1个Element,则返回0.
注意:在C ++中,使用空向量。在C中没有null。;-)
-- There's no null in Haskell, therefore Maybe [Int] is used. Nothing represents null.
测试用例:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
public class SolutionTest {
@Test
public void BasicTests() {
assertEquals(16, Kata.sum(new int[] { 6, 2, 1, 8, 10}));
}
@Test
public void BasicTests1() {
assertEquals(0, Kata.sum(new int[] {}));
}
}
解题
My
public class Kata
{
public static int sum(int[] numbers)
{
if(numbers == null){
return 0;
}
for (int i = 0; i < numbers.length - 1; i++) {
for (int j = 0; j < numbers.length - 1 - i; j++) {
if (numbers[j] > numbers[j + 1]) {
int tmp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = tmp;
}
}
}
int sum = 0;
for (int j = 1; j < numbers.length - 1; j++) {
sum += numbers[j];
}
return sum;
}
}
Other
public class Kata
{
public static int sum(int[] numbers)
{
if (numbers == null || numbers.length == 0 || numbers.length == 1) return 0;
int min,max,sum;
sum = min = max = numbers[0];
for (int i = 1; i < numbers.length; i++)
{
sum += numbers[i];
if (numbers[i] < min) min = numbers[i];
if (numbers[i] > max) max = numbers[i];
}
return sum - min - max;
}
}
import static java.util.stream.IntStream.of;
public class Kata {
public static int sum(int[] numbers) {
return (numbers == null || numbers.length <= 2) ? 0 : of(numbers).sum() - of(numbers).max().getAsInt() - of(numbers).min().getAsInt();
}
}
import java.util.Arrays;
public class Kata
{
public static int sum(int[] numbers)
{
if(numbers == null || numbers.length < 2) return 0;
Arrays.sort(numbers);
return Arrays.stream(numbers).skip(1).limit(numbers.length-2).sum();
}
}
后记
Other的第一个确实聪明呀。