• 13调整数组顺序使奇数位于偶数前面


    题目描述

    输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
     
     
    思路1:

    用辅助数组存,时间复杂度O(N) 空间复杂度O(N)

     1 public class Solution {
     2     public void reOrderArray(int [] array) {
     3         int[] res = new int[array.length];
     4         int j =0;
     5         for(int i =0;i<array.length;i++){
     6             if(array[i]%2!=0)
     7                res[j++]=array[i];     
     8         }
     9         for(int i =0;i<array.length;i++){
    10              if(array[i]%2==0)
    11                res[j++]=array[i];
    12         }  
    13          for(int i=0;i<array.length;i++){
    14             array[i]=res[i];
    15         }
    16     }
    17 }

    思路2:冒泡排序

     1 public class Solution {
     2     
     3     public void reOrderArray(int [] array) {
     4         for(int i = 0;i < array.length-1;i++){
     5             for (int j = 0;j<array.length-i-1;j++){
     6                 if(array[j]%2==0 && array[j+1]%2!=0)
     7                     swap(array,j,j+1);
     8             }
     9         }
    10     }
    11     private void swap(int[] a,int i,int j){
    12         int tem= a[i];
    13         a[i]=a[j];
    14         a[j]=tem;
    15     }
    16 }

    更新20180307

     1 # -*- coding:utf-8 -*-
     2 class Solution:
     3     def reOrderArray(self, a):
     4         # write code here
     5         def swap(a,i,j):
     6             temp =a[i]
     7             a[i] =a[j]
     8             a[j] =temp
     9         for i in range(len(a)):
    10             #for j in range(i,len(a)-1)[::-1]:#向上冒泡
    11             for j in range(0,len(a)-i-1):#向下沉
    12                 if(a[j+1]%2==1 and a[j]%2==0):
    13                     swap(a,j,j+1)
    14         return a

    c++:20180808

    class Solution {
    public:
        void reOrderArray(vector<int> &a) {
            int n = a.size();
            for (int i = 0; i < n; ++i)
                for (int j = 0; j < n-i-1; ++j)
                    if((a[j]%2==0)&&(a[j+1]%2!=0))
                        swap(a,j,j+1);
        }
        void swap(std::vector<int> &a,int i,int j){
            int t = a[i];
            a[i] = a[j];
            a[j] =t;
        }
    };
  • 相关阅读:
    [BZOJ4876][ZJOI2017]线段树
    [FJOI2016]建筑师(斯特林数)
    WC2018伪题解
    [BZOJ3514]CodeChef MARCH14 GERALD07加强版(LCT+主席树)
    [BZOJ2594][WC2006]水管局长加强版(LCT+Kruskal)
    [洛谷3796]【模板】AC自动机(加强版)
    [洛谷3808]【模板】AC自动机(简单版)
    [BZOJ3261]最大异或和
    [BZOJ3439]Kpm的MC密码
    [POI2006]Periods of Words
  • 原文地址:https://www.cnblogs.com/zle1992/p/7839373.html
Copyright © 2020-2023  润新知