题目
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]
分析
解法比较多,可以直接进行排序,在排序时略过偶数,也可以将奇数拿出来,排好序后再放回原来的数组中。
我的解法
import java.util.*;public class Kata {public static int[] sortArray(int[] array) {ArrayList<Integer> odds = new ArrayList<>();ArrayList<Integer> indexs = new ArrayList<>();for (int i = 0; i < array.length; i++) {if (array[i] % 2 != 0){odds.add(array[i]);indexs.add(i);}}Collections.sort(odds);Collections.sort(indexs);for (int i = 0; i < odds.size(); i++) {array[indexs.get(i)]= odds.get(i);}return array;}}
参考解法
import java.util.*;public class Kata {public static int[] sortArray(final int[] array) {// Sort the odd numbers onlyfinal int[] sortedOdd = Arrays.stream(array).filter(e -> e % 2 == 1).sorted().toArray();// Then merge them back into original arrayfor (int j = 0, s = 0; j < array.length; j++) {if (array[j] % 2 == 1) array[j] = sortedOdd[s++];}return array;}}
public class Kata {public static int[] sortArray(int[] array) {for(int i=0 ; i<array.length-1 ; i++){for(int j=i+1; j<array.length ; j++){if(array[i]>array[j] && array[i]%2 == 1 && array[j]%2 == 1){int aux=array[i];array[i]=array[j];array[j]=aux;}}}return array;}}
import java.util.ArrayList;import java.util.Collections;public class Kata {public static int[] sortArray(int[] array) {ArrayList<Integer> oddList = new ArrayList<>(array.length);for (int i = 0; i < array.length; i++) {if (array[i] % 2 == 1) {oddList.add(array[i]);}}Collections.sort(oddList);for (int i = 0, j = 0; i < oddList.size(); i++, j++) {while (array[j] % 2 == 0) {j++;}array[j] = oddList.get(i);}return array;}}
提升
- 使用
stream对数据进行过滤,然后对过滤得到的数组进行排序不失为一种巧妙的方法
