筆試面試之奇偶partition

輸入一個整數數組,調整數組中數字的順序,使得所有奇數位於數組的前半部分,所有偶數位於數組的後半部分。要求時間複雜度爲O(n)

 

方法一:遍歷數組統計出奇數偶數個數,再申請一個數組,放置即可,時復o(n),空復o(n)

方法二:從開頭遍歷,遇到偶數則從後面尋找最接近的一個奇數交換,若找不到,則返回完成。時復o(n方)

方法三:類似於quick sort 從兩頭向中間遍歷,低指針找偶數,高指針找奇數,找到後交換,直至低指針>=高指針,時復o(n)

方法四:STL中的stable_partition算法

 

方法三

bool isEven(int n)
{
      return (n & 1) == 0;
}


void Reorder(int *pData, unsigned int length, bool (*func)(int))
{
      if(pData == NULL || length == 0)
            return;

      int *pBegin = pData;
      int *pEnd = pData + length - 1;

      while(pBegin < pEnd)
      {
            // if *pBegin does not satisfy func, move forward
            if(!func(*pBegin))
            {
                  pBegin ++;
                  continue;
            }

            // if *pEnd does not satisfy func, move backward
            if(func(*pEnd))
            {
                  pEnd --;
                  continue;
            }

            // if *pBegin satisfy func while *pEnd does not,
            // swap these integers
            int temp = *pBegin;
            *pBegin = *pEnd;
            *pEnd = temp;
      }
}

void ReorderOddEven(int *pData, unsigned int length)
{
      if(pData == NULL || length == 0)
            return;

      Reorder(pData, length, isEven);
}

 

方法四:STL的partition源碼


template<typename _BidirectionalIter, typename _Predicate>
    _BidirectionalIter
    __partition(_BidirectionalIter __first, _BidirectionalIter __last,
_Predicate __pred,
bidirectional_iterator_tag)
    {
      while (true) {
while (true)
  if (__first == __last)
    return __first;
  else if (__pred(*__first))
    ++__first;
  else
    break;
--__last;
while (true)
  if (__first == __last)
    return __first;
  else if (!__pred(*__last))
    --__last;
  else
    break;
iter_swap(__first, __last);
++__first;
      }
    }

這個算法的結束條件?

轉貼自:http://zhedahht.blog.163.com/blog/static/25411174200741295930898/

發佈了11 篇原創文章 · 獲贊 0 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章