905|Sort Array By Parity

Given an array A of non-negative(非负整数) integers, return an array consisting of all the even(奇数) elements of A, followed by all the odd(偶数) elements of A.

You may return any answer array that satisfies this condition.

把偶数放前面,把奇数放后面

Example 1:

Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

Note:

1 <= A.length <= 5000
0 <= A[i] <= 5000

第一种做法:两个循环,第一个循环把偶数找出来放到一个新数组,第二个循环把奇数找出来放到新数组里

class Solution {
    public int[] sortArrayByParity(int[] A) {
    
    int []result=new int[A.length];
    int k=0;
    for(int i=0;i<A.length;i++){
        if(A[i]%2==0){
            result[k++]=A[i];
        }
    }
    for(int i=0;i<A.length;i++){
        if(A[i]%2!=0){
            result[k++]=A[i];
        }
    }
    return result;
  }
}

第2中做法:

class Solution {
    public int[] sortArrayByParity(int[] A) {
          int i=0;
          int j=A.length-1;
          while(i<j){
             //A[i]%2==0为偶数,A[i]%2==1为奇数
             //从头开始的数 跟 末尾的数比较是奇数就放到后面去,是偶数就放前面来
              if(A[i]%2 >A[j]%2){
                  int temp=A[i];
                  A[i]=A[j];
                  A[j]=temp;
              }
              //如果从头方向开始比较的数已经是偶数了,往下一个数来继续判断是奇数还是偶数
              if(A[i]%2==0) i++;
              //如果最后一个数已经是奇数了,往前移动一位来判断
              if(A[j]%2==1) j--;
          }
          return A;
  }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值