Skip to content

Latest commit

 

History

History
50 lines (36 loc) · 874 Bytes

File metadata and controls

50 lines (36 loc) · 874 Bytes

905. Sort Array By Parity

Leetcode link

解题思路

简单题,说白了就是把偶数往前丢,然后剩下的奇数往后放就好,直接看代码

C++

class Solution {
 public:
  vector<int> sortArrayByParity(vector<int>& nums) {
    int left = 0, right = nums.size() - 1;
    while (left < right) {
      if (nums[right] % 2 == 0) {
        swap(nums[left++], nums[right]);
      } else {
        right--;
      }
    }
    return nums;
  }
};

Javascript

var sortArrayByParity = function(nums) {
   let left = 0, right = nums.length-1;
    while(left < right) {
        if(nums[right] % 2 === 0) {
            [nums[left], nums[right]] = [nums[right], nums[left]];
            left++;
        } else {
            right--;
        }
    }
    return nums;
};