leetcode_2 Sort Array By Parity II(sort)

  • 题目描述:

    Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.

    Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.

    You may return any answer array that satisfies this condition.

    Example 1:

    Input: [4,2,5,7]
    Output: [4,5,2,7]
    Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.
  • 中文描述:将给定的非负数组进行排序重组,使得下标为奇数,则下标对应的值为奇数,下标为偶数,则对应的值为偶数
  • 解题思路:
    • 思路一:首先对数组遍历一次分别将偶数奇数存放,然后重新遍历数组依次从偶数数组,奇数数组中拿出值为数组赋值,时间复杂度为o(n)空间为o(n)
    • 思路二:将数组按照下标的奇偶性进行遍历,分别遇到第一个偶数下标不为偶数值,奇数下标,不为奇数值,将其互换,时间复杂度o(n)空间o(1)
  • 解题代码:
    • 思路一的c++实现
      class Solution {
      public:
          vector<int> sortArrayByParityII(vector<int>& A) {
              vector<int> even;
              vector<int> odd;
              vector<int>::iterator it;
              for(it=A.begin();it!=A.end();it++)
              {
                  if(*it%2==0)
                  {
                      even.push_back(*it);
                  }
                  else{
                      odd.push_back(*it);
                  }
              }
              int length=A.size();
              int i=0,j=0;
              int cy=0;
              bool flag=true;
              while(cy<length)
              {
                  if(flag)
                  {
                      A[cy++]=even[i++];
                      flag=false;
                  }
                  else{
                      A[cy++]=odd[j++];
                      flag=true;
                  }
              }
              return A;
              
          }
      };
      
    • 思路二的python3实现
      class Solution:
          def sortArrayByParityII(self, A: List[int]) -> List[int]:
              length=len(A)
              ev_cy,od_cy=0,1
              while ev_cy<length and od_cy<length:
                  if A[ev_cy]%2==0:
                      ev_cy+=2
                  elif A[od_cy]%2==1:
                      od_cy+=2
                  else:
                      A[ev_cy],A[od_cy]=A[od_cy],A[ev_cy]
                      ev_cy+=2
                      od_cy+=2
              return A
      
  • 语法总结:
    • c++:迭代器声名语句:vector<int> iterator; vector.push_back() ;bool flag=true;vector.pop() 删除栈顶元素,无返回值。
    • python:flag=True;list 存在属性 list.pop(i)弹出某一元素,返回值为弹出元素值,默认值为末尾元素。

猜你喜欢

转载自www.cnblogs.com/zydxx/p/10428174.html