TreeviewCopyright © aleen42 all right reserved, powered by aleen42

905. 按奇偶排序数组

https://leetcode-cn.com/problems/sort-array-by-parity/

Java

/*
 * @Author: Goog Tech
 * @Date: 2020-08-16 11:39:16
 * @LastEditTime: 2020-08-16 11:39:27
 * @Description: https://leetcode-cn.com/problems/sort-array-by-parity/
 * @FilePath: \leetcode-googtech\#905. Sort Array By Parity\Solution.java
 * @WebSite: https://algorithm.show/
 */

class Solution {
    // 双指针法
    public int[] sortArrayByParity(int[] A) {
        int left = 0, right = A.length - 1;
        while(left < right) {
            while(left < right && A[left] % 2 == 0) left++;
            while(left < right && A[right] % 2 != 0) right--;
            int temp = A[left];
            A[left] = A[right];
            A[right] = temp;
        }
        return A;
    }
}

Python

'''
Author: Goog Tech
Date: 2020-08-16 11:39:20
LastEditTime: 2020-08-16 11:39:46
Description: https://leetcode-cn.com/problems/sort-array-by-parity/
FilePath: \leetcode-googtech\#905. Sort Array By Parity\Solution.py
WebSite: https://algorithm.show/
'''

class Solution(object):
    def sortArrayByParity(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        i = 0
        for j in range(len(A)):
            if A[j] % 2 == 0:
                A[i], A[j] = A[j], A[i]
                i += 1
        return A
Copyright © GoogTech 2021 all right reserved,powered by GitbookLast update time : 2021-09-15 01:55:05

results matching ""

    No results matching ""