Leetcode 905. Sort Array By Parity

题目

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

**Level: ** Easy

Discription:

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:
    vector<int> sortArrayByParity(vector<int>& A) {
        int i=0;
        int j=A.size()-1;
        
        while(i<j)
        {
            if(!(A[i]%2))
            {
                i++;
                continue;
            }
            if(A[j]%2)
            {
                j--;
                continue;
            }
            swap(A[i],A[j]);
        }
        return A;
    }
};

思考

  • 算法时间复杂度为O(N),空间复杂度为O(1)。
  • 使用双指针的思想,一个指针从左往右遍历,一个从右往左。
  • if中continue的使用,相比于再套一个while,要节省代码。
posted @ 2019-01-03 15:31  我的小叮当  阅读(102)  评论(0编辑  收藏  举报