劍指offer 面試21題


面試21題:

題目:調整數組的順序使奇數位於偶數前面

題一:輸入一個整數數組,實現一個函數來調整該數組中數字的順序,使得所有奇數位於數組的前半部分,所有偶數位於數組的后半部分。

解題思路:使用兩個指針,第一個指針初始化指向數組的第一個數字,從前向后移動,遇到偶數就停下來;第二個指針指向數組的最后一個數字,從后向前移動,遇到奇數就停下來,交換兩個指針指向的元素,直到兩個指針相遇。

解題代碼:

# -*- coding:utf-8 -*-
class Solution:
    def reOrderArray(self, array):
        # write code here
        if array==None or len(array)==0:
            return
        pBegin=0
        pEnd=len(array)-1
        while (pBegin<pEnd):
            while pBegin<pEnd and not self.isEven(array[pBegin]):
                pBegin += 1
            while pBegin<pEnd and self.isEven(array[pEnd]):
                pEnd -= 1
            if pBegin<pEnd:
                temp=array[pBegin]
                array[pBegin]=array[pEnd]
                array[pEnd]=temp
        return array

    def isEven(self,number):
        return number & 1==0

 

題二:在題一基礎上,要求奇數和奇數,偶數和偶數的相對位置保持不變。

解題代碼:

# -*- coding:utf-8 -*-
class Solution:
    def reOrderArray(self, array):
        # write code here
        res1=[]
        res2=[]
        for i in array:
            if i%2!=0:
                res1.append(i)
            else:
                res2.append(i)
        return res1+res2

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM