Sort the odd(6Kyu) - 图1

题目

You will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions. 你将得到一个数字数组。你必须把奇数按升序排序,而把偶数留在原来的位置

例子

[7, 1] => [1, 7] [5, 8, 6, 3, 4] => [3, 8, 6, 5, 4] [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] => [1, 8, 3, 6, 5, 4, 7, 2, 9, 0]

原题链接

分析

解法比较多,可以直接进行排序,在排序时略过偶数,也可以将奇数拿出来,排好序后再放回原来的数组中。

我的解法

  1. import java.util.*;
  2. public class Kata {
  3. public static int[] sortArray(int[] array) {
  4. ArrayList<Integer> odds = new ArrayList<>();
  5. ArrayList<Integer> indexs = new ArrayList<>();
  6. for (int i = 0; i < array.length; i++) {
  7. if (array[i] % 2 != 0){
  8. odds.add(array[i]);
  9. indexs.add(i);
  10. }
  11. }
  12. Collections.sort(odds);
  13. Collections.sort(indexs);
  14. for (int i = 0; i < odds.size(); i++) {
  15. array[indexs.get(i)]= odds.get(i);
  16. }
  17. return array;
  18. }
  19. }

参考解法

  1. import java.util.*;
  2. public class Kata {
  3. public static int[] sortArray(final int[] array) {
  4. // Sort the odd numbers only
  5. final int[] sortedOdd = Arrays.stream(array).filter(e -> e % 2 == 1).sorted().toArray();
  6. // Then merge them back into original array
  7. for (int j = 0, s = 0; j < array.length; j++) {
  8. if (array[j] % 2 == 1) array[j] = sortedOdd[s++];
  9. }
  10. return array;
  11. }
  12. }
  1. public class Kata {
  2. public static int[] sortArray(int[] array) {
  3. for(int i=0 ; i<array.length-1 ; i++){
  4. for(int j=i+1; j<array.length ; j++){
  5. if(array[i]>array[j] && array[i]%2 == 1 && array[j]%2 == 1){
  6. int aux=array[i];
  7. array[i]=array[j];
  8. array[j]=aux;
  9. }
  10. }
  11. }
  12. return array;
  13. }
  14. }
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. public class Kata {
  4. public static int[] sortArray(int[] array) {
  5. ArrayList<Integer> oddList = new ArrayList<>(array.length);
  6. for (int i = 0; i < array.length; i++) {
  7. if (array[i] % 2 == 1) {
  8. oddList.add(array[i]);
  9. }
  10. }
  11. Collections.sort(oddList);
  12. for (int i = 0, j = 0; i < oddList.size(); i++, j++) {
  13. while (array[j] % 2 == 0) {
  14. j++;
  15. }
  16. array[j] = oddList.get(i);
  17. }
  18. return array;
  19. }
  20. }

提升

  1. 使用 stream 对数据进行过滤,然后对过滤得到的数组进行排序不失为一种巧妙的方法