每日一道Leetcode算法——Sort Array By Parity——2019.01.31

中文:

给定一个非负整数数组A,返回一个由A的所有偶数元素组成的数组,后跟A的所有奇数元素。 您可以返回满足此条件的任何答案数组。

 

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. 1 <= A.length <= 5000
  2. 0 <= A[i] <= 5000

英文:

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. 1 <= A.length <= 5000
  2. 0 <= A[i] <= 5000

解题思路:

题目没有说不让使用额外空间,而且只要求偶数在前,奇数灾后在后,没有要求奇偶数的顺序。

所以我们新建一个数组,和原数组长度一致。

然后循环原数组,判断是偶数,则从新数组的前面向后面放,如果是奇数,则从新数组的后面向前面放。

这样只循环一次,效率比较高。

package cn.leetcode.easy;

import java.util.Arrays;

/**
 * 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.
 *
 * @author kimtian
 * @date 2019.01.31
 * @num 905
 */
public class Sort_Array_By_Parity {
    /**
     * 题目没有说不让使用额外空间,而且只要求偶数在前,奇数灾后在后,没有要求奇偶数的顺序。
     * 所以我们新建一个数组,和原数组长度一致。
     * 然后循环原数组,判断是偶数,则从新数组的前面向后面放,如果是奇数,则从新数组的后面向前面放。
     * 这样只循环一次,效率比较高。
     *
     * @param A 待排序数组
     * @return 排序后数组
     */
    public static int[] sortArrayByParity(int[] A) {
        //创建一个新数组
        int[] newInt = new int[A.length];
        //定义一个新数组从头开始的指针
        int j = 0;
        //定义一个从新数组尾巴开始的指针
        int z = newInt.length - 1;
        //循环拿出老数组的数据
        for (int i = 0; i < A.length; i++) {
            //如果是偶数,则从数组的前往后放数据
            if (A[i] % 2 == 0) {
                //放入数据
                newInt[j] = A[i];
                //移动指针
                j++;
            }
            //奇数从从后往前放数据
            else {
                //放入数据
                newInt[z] = A[i];
                //移动指针
                z--;
            }
        }
        return newInt;

    }

    /**
     * 测试
     *
     * @param args
     */
    public static void main(String[] args) {
        int[] A = new int[]{1, 3, 5, 4, 2, 6, 7, 8, 0};
        System.out.println(Arrays.toString(sortArrayByParity(A)));
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值