Highest and Lowest && Find the stray number

一、Highest and Lowest

首刷java题目,题目如下:

  1. In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.
  2. Example:
    HighAndLow("1 2 3 4 5") // return "5 1"
    HighAndLow("1 2 -3 4 5") // return "5 -3"
    HighAndLow("1 9 3 4 -5") // return "9 -5"
  3. All numbers are valid Int32, no need to validate them.
  4. There will always be at least one number in the input string.
  5. Output string must be two numbers separated by a single space, and highest number is first.

题目大意是说:给你一数字字符串(每一个数字之间是空格隔开),找出字符串里面最大和最小的数字,字符串里面所有的数字都是有效的,不需要进行验证。

解题思路:由于字符串是由空格隔开的,就是用String的split()进行字符串的分割成字符串数组,声明一个int类型的数组并赋值,然后利用Arrays类型进行数组的排序,排成增序,所以只需要取出int数组里面的第一个元素跟最后一个即可。

import java.util.Arrays;
public class Kata {
  public static String HighAndLow(String numbers) {
   String[] num= numbers.split(" ");
   int len=num.length;
   int [] a=new int[len];
   for(int i=0;i<len;i++){
     a[i]=Integer.parseInt(num[i]);
   }
   Arrays.sort(a);
   int min=a[0];
   int max=a[len-1];
   String result=max+" "+min;
   return result;
  }
}

附上Kata大佬写的:

import java.util.*;
import java.util.stream.*;

public class Kata {
  public static String HighAndLow(String numbers) {
    IntSummaryStatistics summary = Arrays
      .stream(numbers.split(" "))
      .collect(Collectors.summarizingInt(n -> Integer.parseInt(n)));
    return String.format("%d %d", summary.getMax(), summary.getMin());
  }
}

二、Find the stray number

  1. You are given an odd-length array of integers, in which all of them are the same, except for one single number.

    Complete the method which accepts such an array, and returns that single different number.

    The input array will always be valid! (odd-length >= 3)

  2. Examples:

[1, 1, 2] ==> 2
[17, 17, 3, 17, 17, 17, 17] ==> 3

题目大意:给出一个长度为奇数且大于3的数组,找出其中不同的那一个数字。

解题思路:直接进行数组的排序,再进行比较,第一个元素跟第二个元素如果相等就直接返回最后一个元素,否则就是第一个元素,因为数组的元素已经排好序了,不同的那一个数要么是最大的,要么是最小的。

import java.util.Arrays;

class Solution {
  static int stray(int[] numbers) {
    Arrays.sort(numbers);
    return numbers[0] == numbers[1] ? numbers[numbers.length-1] : numbers[0];
  }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值