Java刷题(四)

Codewars 刷题第四天,数组问题:

题目:

  You have an array of numbers.

  Your task is to sort ascending odd numbers but even numbers must be on their places.

  Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.

Example:

  sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4];

题目要求:

       将数组中的奇数排序,偶数位置不变

解析:    

 遍历记录奇数的位置和内容,排序。可以使用Stream类型的sorted方法。

答案:(已AC)

a.

b.

 

c.

 

d.

 

这是四个略微不同的解决方案,bc缺少排序部分,对于这个数组来说,首先是未知长度这一点,当然通常一点,也可以用获取来的长度定义int [ ] id=new int [array.length],但是作者并不推荐这样做。处理未知长度的方法有很多,上述四种方法中HashMap,Vector,Arrays,IntStream,都是较为迅速的方法。

猜你喜欢

转载自www.cnblogs.com/Jaiken/p/8955905.html