• 第一种办法是声明一个新数组,然后遍历原数组将偶数放入新数组的前面,奇数放到新数组的后面

    /**
     * @param {number[]} A
     * @return {number[]}
     */
    var sortArrayByParity = function(A) {
        let s =0,j=A.length-1,b = []
        for(let i =0; i< A.length; i++) {
            if(A[i]%2 == 0) {
                b[s] = A[i]
                s++
            } else {
                b[j] = A[i]
                j--
            }
        }
        return b
    };

    第二种是原地算法,用两个指针从数组前后同时遍历,遇到前奇后偶的就叫唤一下

    /**
     * @param {number[]} A
     * @return {number[]}
     */
    var sortArrayByParity = function(A) {
        let i=0;j=A.length-1
        while (i <j) {
            if(A[i]%2 >A[j]%2) {
                let tmp = A[j]
                A[j] = A[i]
                A[i] = tmp
            }
            if (A[i]%2==0) i++
            if (A[j]%2==1) j--
        }
        return A
    };

    题目

    给定一个非负整数数组 A,返回一个数组,在该数组中, A 的所有偶数元素之后跟着所有奇数元素。


  • leetcode中很多有关数组的题目都可以用双指针解决,例如之前做的一道要求在原地(in-place)移除元素就是用双指针做的 LeetCode 27. 移除元素 – 昨日当年

    使用思路是:在需要进行原地操作的题中 声明两个指针, 一个指针用来作索引正常遍历,另一个指针指向需要做替换操作的元素

    就比如这道 Move Zeroes

    /**
     * @param {number[]} nums
     * @return {void} Do not return anything, modify nums in-place instead.
     */
    var moveZeroes = function(nums) {
        let i = j =0
        for(;i<nums.length; i++) {
            if(nums[i]!==0) {
                nums[j] = nums[i]
                j++
            }
        }
        for(; j<i; j++) {
            nums[j] = 0
        }
    };

    i 作 index 用来遍历 nums

    找到非0元素时 把值赋给 nums[j]

    则在 for 循环结束时 nums[0] 至 nums[j] 为非0元素

    即数组中存在 j+1 个非0元素 ,然后用原本数组的长度(i+1)减去非0元素 剩下的赋为0就行了

    Move Zeroes

    Given an array nums, write a function to move all 0‘s to the end of it while maintaining the relative order of the non-zero elements.

    Example:

    Input: [0,1,0,3,12]
    Output: [1,3,12,0,0]

    Note:

    1. You must do this in-place without making a copy of the array.
    2. Minimize the total number of operations.