剑指offer题12

来源:互联网 发布:用sql语言创建数据库 编辑:程序博客网 时间:2024/05/21 21:38
package jianzhioffer;import java.util.LinkedList;import java.util.Scanner;/** * 输入一个整数数组,实现一个函数来调整该数组中数字的顺序, * 使得所有的奇数位于数组的前半部分,所有的偶数位于位于数组的后半部分, * 并保证奇数和奇数,偶数和偶数之间的相对位置不变。 * */public class Solution12 {public static void reOrderArray(int[] array){//空间复杂度为O(1),时间复杂度为O(n),类插入排序for(int i = 0;i<array.length;i++){int target = array[i];if(array[i] %2 == 1){int j = i;while(j>=1 && array[j-1]%2 == 0){array[j] = array[j-1];j--;}array[j] = target;}}}/*public static void reOrderArray(int [] array) { //利用两个队列或者两个数组分别表示奇、偶,最后按序输出即可LinkedList<Integer> odd = new LinkedList<Integer>(); //或者设置:int[] odd = new int[array.length];LinkedList<Integer> even = new LinkedList<Integer>();int oddnum = 0;for(int i = 0;i<array.length;i++){if(array[i] % 2 == 0){even.add(array[i]);}else {odd.add(array[i]);oddnum++;}}for(int i = 0;!odd.isEmpty();i++){ //测试系统结果,没有输出,要求输出为空array[i] = odd.pop();}for(int i = 0;!even.isEmpty();i++){array[i+oddnum] = even.pop();}while(!odd.isEmpty()){ //eclipse控制台输出System.out.println(odd.pop());}while(!even.isEmpty()){System.out.println(even.pop());}    }*/public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();int[] array = new int[n];for(int i = 0;i<n;i++){array[i] = sc.nextInt();}reOrderArray(array);}}

原创粉丝点击