版权声明:转载请注明出处 https://blog.csdn.net/github_37412255/article/details/79796166
问题描述:一个数组当中有不同类型的数字,如:奇数、偶数和小数。如何将这些数据整理为奇数放在前面,偶数放在中间,小数放在后面。而且要求尽量节省空间。
package org.leetcode;
import java.util.*;
/**
* leetcode problem
* @author Weebing
* @since 2018.4.2
*/
class Solution {
public Map<Integer, Double> insertTheThirdNum(double[] nums) {
Map<Integer, Double> collect = new HashMap<Integer, Double>();
int index = 0;
for (int i = 0; i < nums.length; i++) {
if (collect.size() == 0) {
collect.put(index++, nums[i]);
} else if ((nums[i] + 1) % 2 == 0) { // 奇数
for (int j = index - 1; j >= 0; j--) {
collect.put(j + 1, collect.get(j));
}
collect.put(0, nums[i]);
index++;
} else if (nums[i] % 2 == 0) { // 偶数
for (int j = 0; j < collect.size(); j++) {
if ((collect.get(j) % 2 != 0) && ((collect.get(j) + 1) % 2 != 0)) {
for (int k = collect.size() - 1; k >= j; k--) {
collect.put(k + 1, collect.get(k));
}
collect.put(j, nums[i]);
index++;
break;
} else if (collect.get(j) % 2 == 0) {
for (int k = collect.size() - 1; k >= j; k--) {
collect.put(k + 1, collect.get(k));
}
collect.put(j, nums[i]);
index++;
break;
} else if (j == collect.size() - 1) {
collect.put(index++, nums[i]);
break;
}
}
} else { // 第三种数
collect.put(index++, nums[i]);
}
}
return collect;
}
public static void main(String[] args) {
Solution s = new Solution();
double[] nums = new double[] {
1.1,1.2,1,2,3,4,5,6,7,3.2,8,10
};
Map<Integer, Double> list = s.insertTheThirdNum(nums);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
如有任何问题,欢迎指正